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?
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.
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);
}
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.