error: invalid operands to binary + char * [duplic

2019-04-17 16:26发布

问题:

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?

回答1:

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.



回答2:

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);

}


回答3:

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.



标签: c char