我創建了一個聯盟,並將不同類型的數組放入其中。我按順序打印輸出結果,我真的不明白一些觀點。聯盟的不同類型的陣列的打印輸出
1)即使內容不同,爲什麼我的char數組的長度始終爲8?裏面只有「你好」。爲什麼產量是「貓搖滾!」當我嘗試第二次打印時。我沒有在陣列中放置任何類似的東西。
2)再次長度問題。我的所有陣列的長度都是8,甚至是聯盟的長度。爲什麼?
3)我的最後一個問題是,當我第二次嘗試打印時,雙號碼的值發生了變化。
我發佈你我的代碼,並把我得到。對不起,很長的帖子,但我真的很困惑。
char: hello, 8
double: 5.557111111111111, 8
int: 1937006915 1668248096 8555, 8
char: Cats rock!
double: 0.000000000000000
int: 1937006915 1668248096 8555
size of union: 8
我的代碼
#define NUM1 5.557111111111111
#define NUM2 1937006915
#define NUM3 1668248096
#define NUM4 8555
#include <stdio.h>
/*created an union*/
typedef union {
char * array1;
double num;
int * array2;
} myunion;
int main(int argc, char ** argv)
{
/* declaring union variable */
myunion uni;
/* creating my string */
char strarray[] = "hello";
/* declare an int array*/
int numarray[] = { NUM2, NUM3, NUM4 };
/* assign the string to the char pointer in the union */
uni.array1 = strarray;
/* print the union and the sizeof of the pointer */
printf("char: %s, %zu\n", uni.array1,sizeof(uni.array1));
/* assign NUM1 to the double part of union */
uni.num = NUM1;
/* print the double and its sizeof */
printf("double: %10.15f, %zu\n", uni.num, sizeof(uni.num));
/* assign array2 of union to the numarray */
uni.array2 = numarray;
/* print the values and the sizeof */
printf("int: %d %d %d, %zu\n", uni.array2[0], uni.array2[1], uni.array2[2], sizeof(uni.array2));
/* print the char array, double and int array */
printf("\nchar: %s \ndouble: %10.15f \nint: %d %d %d\n",uni.array1, uni.num, uni.array2[0], uni.array2[1], uni.array2[2]);
/* print the size of the union */
printf("size of union: %zu\n", sizeof(uni));
return 0;
}
你知道聯盟實際上是什麼嗎? – Dan 2012-02-18 19:01:57