2012-02-18 71 views
1

我創建了一個聯盟,並將不同類型的數組放入其中。我按順序打印輸出結果,我真的不明白一些觀點。聯盟的不同類型的陣列的打印輸出

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; 
} 
+0

你知道聯盟實際上是什麼嗎? – Dan 2012-02-18 19:01:57

回答

2

sizeof(uni.array1)始終是8個在64位平臺和4個32位的人,因爲它是採用指針的大小,不知道你有多少數據相信威力在那個指針後面。類似於數組。你指向一個數組的C指針是「愚蠢的」,不理解數組的大小 - 你需要分別傳遞這些信息。

這涵蓋了您的問題第1部分和第2部分。我們希望在此回答特定問題,因此請隨時將您的第三個問題轉到單獨的帖子。

+1

是的,這裏的問題是,他認爲指針是一個數組,當它甚至不接近時。 – 2012-02-18 18:58:01

1

你的聯合實際上並不包含數組,它只包含兩個指針之一。你的機器上指針的大小是8。如果你想在陣列成爲聯盟的一部分,做這種方式

typedef union { 
    char array1[MAX*8]; /* or whatever */ 
    double num; 
    int array2[MAX]; 
} myunion; 

的陣列必須有固定的長度。這是編譯時類型的本質。

+0

你是對的我用錯了詞。 – 2012-02-18 18:58:54