Error: incompatible types when assigning to type ‘

2020-07-30 01:00发布

I'm trying to assign the values of a struct to a map but the following error message appears after compiling:

error: incompatible types when assigning to type ‘char[25]’ from type ‘char *’ 

in

map[i].n=m.n

My struct is defined this way:

struct m1{
int c;
char n[25];
int q_m;
int q;};

Part of my code:

    struct m1 m;
    struct m1 *map = 0;
    scanf("%d",&m.c);
    scanf("%s",&m.n);
    scanf("%d",&m.q_m);
    scanf("%d",&m.q);

    map[i].c=m.c;
    map[i].n=m.n;
    map[i].q_m=m.q_m;
    map[i].q=m.q;

标签: c
7条回答
Melony?
2楼-- · 2020-07-30 01:59

Array expressions may not be the target of an assignment; the = operator isn't defined to copy the contents of one array to the other.

If n is meant to hold a 0-terminated string, use strcpy:

strcpy( map[i].n, m.n );

If n is meant to hold a non-0-terminated string (or a sequence of characters with embedded 0 values), use memcpy:

memcpy( map[i].n, m.n, sizeof map[i].n );

Unless it is the operand of the sizeof or unary & operators, or is a string literal being used to initialize another array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element.

That's why you got the error message you did; the expression m.n has type "25-element array of char"; since it wasn't the operand of the sizeof or unary & operators, it was converted to type char *. map[i].n wasn't converted (it stayed type char [25]), but as I said earlier, array expressions may not be the target of the assignment operator.

查看更多
登录 后发表回答