Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add two strings?

#include <stdio.h>
int main ()
{
    char a[] = "My name is";
    char b[] = "kamran";

    printf("%s %s", a+b);

    return(0);

}

I was trying to add two strings but getting error of "Invalid operands to binary"

like image 393
kamran hassan Avatar asked Dec 06 '22 18:12

kamran hassan


2 Answers

In this expression

a+b

the array designators are implicitly converted to pointers to the first characters of the strings. So in fact you are trying to add two pointers of type char *.

From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

However operator + is not defined for pointers in C and C++.

If you indeed want to add two strings then the result of the operation will be a third string that contains the first two strings.

There are two approaches. Either you declare a third character array large enough to contain the first two strings. Or you need to allocate dynamically memory for the resulted string.

For example

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main( void )
{
    char a[] = "My name is";
    char b[] = "kamran";
    char c[sizeof( a ) + sizeof( b )];

    strcpy( c, a );
    strcat( c, " " );
    strcat( c, b );

    puts( c );

    char *d = malloc( sizeof( a ) + sizeof( b ) );

    if (  d )
    { 
        strcpy( d, a );
        strcat( d, " " );
        strcat( d, b );

        puts( d );
    }

    free( d );
}

The program output is

My name is kamran
My name is kamran
like image 174
Vlad from Moscow Avatar answered Jan 03 '23 05:01

Vlad from Moscow


You can concatenate b to a like this:

char a[18] = "My name is "; // a needs to be big enough
char b[] = "kamran";

strcat(a, b);

printf("%s", a);

To use strcat() you need to include string.h.

like image 22
Viktor Simkó Avatar answered Jan 03 '23 04:01

Viktor Simkó