Char array in a struct - incompatible assignment?

2019-01-10 20:21发布

This question already has an answer here:

I tried to find out what a struct really 'is' and hit a problem, so I have really 2 questions:

1) What is saved in 'sara'? Is it a pointer to the first element of the struct?

2) The more interesting question: Why doesn't it compile? GCC says "test.c:10: error: incompatible types in assignment" and I can't figure out why... (This part has been solved by your answers already, great!)

#include <stdio.h>

struct name {
    char first[20];
    char last[20];
};

int main() {
    struct name sara;
    sara.first = "Sara";
    sara.last = "Black";
    printf("struct direct: %x\n",sara);

    printf("struct deref: %x\t%s\n", *sara, *sara);


}

Thanks for your help!

标签: c struct char
8条回答
【Aperson】
2楼-- · 2019-01-10 21:17

use strncpy to make sure you have no buffer overflow.

char name[]= "whatever_you_want";
strncpy( sara.first, name, sizeof(sara.first)-1 );
sara.first[sizeof(sara.first)-1] = 0;
查看更多
贼婆χ
3楼-- · 2019-01-10 21:21

You can use strcpy to populate it. You can also initialize it from another struct.

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

struct name {
    char first[20];
    char last[20];
};

int main() {
    struct name sara;
    struct name other;

    strcpy(sara.first,"Sara");
    strcpy(sara.last, "Black");

    other = sara;

    printf("struct: %s\t%s\n", sara.first, sara.last);
    printf("other struct: %s\t%s\n", other.first, other.last);

}
查看更多
登录 后发表回答