~~~
#include <stdio.h>
#include <string.h>
struct TStudent
{
long int ID;
union{
char name[10];
char mingzi[11];
};
char dept[17];
};
int main()
{
TStudent stu;
strcpy(stu.name,"zh");
strcpy(stu.dept,"computer science");
printf("student`s mingzi is:%s\n",stu.mingzi);
printf("student`s name is:%s\n",stu.name);
printf("student`s department is:%s\n",stu.dept);
}
~~~
**疑**:以上代碼輸出結果是什么,為什么?
……………………………………………………………………………………………………………………………………
參考解答:
~~~
union{
? ? char name[10];
? ? char mingzi[11];
??};
~~~
定義這個就代表name[10]和mingzi[11]共享同一塊內存。這里順便提一下,mingzi[11]的空間大于name[10],所以申請空間的時候以union里面最大的字段為準。假如
~~~
union?
{
? ?? ? char name[10];
? ?? ? char mingzi[11];
}??UN_NAME;
~~~
那么sizeof(UN_NAME) 應該等于11。即取最大的字段的空間。當然這里不涉及字節對齊問題。
所以當strcpy(stu.name,"zh");執行這句的時候,mingzi[11]的內存空間也被賦值了"zh",所以最后打印兩者的結果是一樣的。
======= welcome to my HomePage([*http://blog.csdn.net/zhanxinhang*](http://blog.csdn.net/zhanxinhang)) to have a?communication =======