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