합집합이 정의되고 정수 값이 지정됩니다. 필요한 배열 크기가 추정됩니다. 다음 값은 공용체에 정의됩니다. 그러나 바이트 배열 값을 인쇄 할 수 없습니다 (즉, 다음 코드의 마지막 부분은 인쇄되지 않습니다). 을 감안할 때 :int 값에서 바이트 배열 값을 추출 할 수 없습니다.
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);
다음 인쇄되지 않은 주에서
union {
unsigned int integer;
//unsigned char byte[4];
unsigned char* byte;
} foo;
() : 노동 조합에서
for (i=numberOfBytes; i >= 0;i--) {
printf("%x ", foo.byte[i]);
} printf("\n");
배열은 포인터와 다릅니다. 편집 : 조합에 바이트 배열이있는 경우 int는 처음 4 바이트를 겹칩니다. 공용체가 대신 포인터를 가지고있을 때, int는 포인터 자체가 겹쳐집니다. 포인터가 가리키는 처음 4 바이트가 아닙니다. – immibis
노동 조합에서는 동일한 공간을 공유합니다. 수정 된 배열 크기를 설정하는 대신 어떻게 해결해야합니까? – Babbit