字符数组的结构 - 不兼容的分配?
问题描述:
我试图找出什么是真正的结构是,撞上了问题,所以我真的有2个问题:
I tried to find out what a struct really 'is' and hit a problem, so I have really 2 questions:
1)什么是保存在萨拉?它是一个指向该结构的第一个元素?
1) What is saved in 'sara'? Is it a pointer to the first element of the struct?
2)更有趣的问题:为什么不把它编译?
GCC说test.c以10:错误:不兼容的类型分配,我想不通为什么...
(这部分已经解决了你的答案已经,太棒了!)
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);
}
感谢您的帮助!
答
这无关与结构 - 在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" );
或你的code:
strcpy( sara.first, "Sara" );