结构中的字符数组 - 不兼容的分配? [英] Char array in a struct - incompatible assignment?
问题描述
我试图找出一个结构到底是什么并遇到了一个问题,所以我真的有两个问题:
I tried to find out what a struct really 'is' and hit a problem, so I have really 2 questions:
1) 'sara' 中保存了什么?它是指向结构的第一个元素的指针吗?
1) What is saved in 'sara'? Is it a pointer to the first element of the struct?
2) 更有趣的问题:为什么不编译?GCC 说test.c:10: error: incompatible types in assignment",我不知道为什么......(这部分已经被你的回答解决了,太好了!)
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
",sara);
printf("struct deref: %x %s
", *sara, *sara);
}
感谢您的帮助!
推荐答案
这与结构无关 - C 中的数组不可赋值:
This has nothing to do with structs - arrays in C are not assignable:
char a[20];
a = "foo"; // error
你需要使用strcpy:
you need to use strcpy:
strcpy( a, "foo" );
或在您的代码中:
strcpy( sara.first, "Sara" );
这篇关于结构中的字符数组 - 不兼容的分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!