2014-02-25 45 views
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"); 
+0

數組與指針不一樣。編輯:當聯合有字節數組時,int重疊前4個字節。當union有一個指針時,int重疊指針本身 - 不是指針指向的前4個字節。 – immibis

+0

在工會中,他們共享相同的空間。我們應該如何解決這個問題,而不是設置固定的數組大小? – Babbit

回答

2

在你的工會,foo.byte是一個指向的內存區域。這:

foo.byte = malloc(sizeof(unsigned char)*numberOfBytes); 

被設置foo.byte的指針,你動態分配的內存區域。然後這樣的:

foo.integer = targetValue; 

覆蓋該指針與價值。

那麼這個:

for (i=numberOfBytes; i >= 0;i--) { 
    printf("%x ", foo.byte[i]); 
} printf("\n"); 

會嘗試去參考targetValue的價值,這將可能給你一個段錯誤。

問題是,既然您將targetValue聲明爲int,它將始終爲sizeof(int)個字節長。沒有理由動態分配它。

您可以將結構變更爲:

union { 
    unsigned int integer; 
    unsigned char byte[sizeof(int)]; 
} foo; 

我假設你正在嘗試做的是找出的最小字節數編碼targetValue的價值,創造正是大小的聯合。

另一件關於工會的理解是,他們總是佔用最大成員的空間,所以即使動態分配工會,也必須至少使sizeof(int)長,否則你會每當你寫入int時就會破壞鄰近的內存。

也許你需要重新思考你正在嘗試做什麼,並從不同的角度來接近它。