#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) to
have a communication =======