我创建了一个联盟,并将不同类型的数组放入其中。我按顺序打印输出结果,我真的不明白一些观点。联盟的不同类型的阵列的打印输出
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