0

Possible Duplicate:
C String Concatenation

have the following code:

        char *doencode(const unsigned char *input, int length)
        {
        //irrelevant code
        }

        char *fname, *lname;
        char *encoded, *name;

        name = fname + "|" + lname;
        encoded = doencode(name, 30);

and I get this error: invalid operands to binary +

How can I combine fname & | & lname?

Community
  • 1
  • 1
Sam Reina
  • 305
  • 1
  • 7
  • 22

3 Answers3

8

You cannot concatenate char* and char[] (the "|") or any permutation of using +. Use strncat() or snprintf() instead and ensure the destination buffer has enough memory to store the final string.

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • will it be easier if I replace | with \0 ? – Sam Reina Jan 08 '13 at 16:41
  • @SamReina, nope. You still need to use a function to concatenate strings. Replacing the `"|"` with a `"\0"` changes nothing regarding the types involved. – hmjd Jan 08 '13 at 16:44
4

the C is not like java script. This is not correct in c:

name = fname + "|" + lname;

you can do it in this way:

sprintf(name,"%s|%s", fname, lname);

The name pointer should be pointed to sufficient memory space.

name = malloc(strlen(fname)+strlen(lname) + 2);

+2: +1 for "|" and +1 for null at the end of the string

Example

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

int main()
{
    char *fname, *lname, *name;

    printf("Enter your first name: ");
    scanf ("%ms", &fname);

    printf("Enter your last name: ");
    scanf (" %ms", &lname);

    name = malloc(strlen(fname)+strlen(lname) + 2);
    sprintf(name,"%s|%s", fname, lname);

    printf("name = %s\n",name);

}
MOHAMED
  • 41,599
  • 58
  • 163
  • 268
0

You can't simply add strings together in C because strings are actually just pointers to character arrays. What you have to do is allocate storage for a new string and copy the two strings per character into it.

Telgin
  • 1,614
  • 10
  • 10