0
定义了一个联合,并给出一个整数值。估计所需的阵列大小。以下值被定义为工会。但是,字节数组值无法打印(即以下代码的最后一部分未打印)。 考虑:无法从int值中提取字节数组值
union {
unsigned int integer;
//unsigned char byte[4];
unsigned char* byte;
} foo;
在main()
int i;
int numberOfBytes = 1;
int targetValue = 123456789;
int sum = 0;
sum = pow(16, numberOfBytes);
while (sum < targetValue) {
//printf("Trying value: %d \n", (16^numberOfBytes));
numberOfBytes++;
sum += pow(16, numberOfBytes);
}
numberOfBytes++; // add 1 more byte space
printf("Number of Bytes: %d \n", numberOfBytes);
printf("Sum: %d \n", sum);
foo.byte = malloc(sizeof(unsigned char)*numberOfBytes);
if (foo.byte == NULL)
printf("malloc fail\n");
// clear foo
for (i=numberOfBytes; i >= 0;i--) {
foo.byte[i] = 0;
}
foo.integer = targetValue;
printf("Trying value: %d \n", foo.integer);
下不打印:
for (i=numberOfBytes; i >= 0;i--) {
printf("%x ", foo.byte[i]);
} printf("\n");
数组与指针不一样。编辑:当联合有字节数组时,int重叠前4个字节。当union有一个指针时,int重叠指针本身 - 不是指针指向的前4个字节。 – immibis
在工会中,他们共享相同的空间。我们应该如何解决这个问题,而不是设置固定的数组大小? – Babbit