2012-07-11 57 views
1
#include <stdio.h> 

int main() { 
    int *a[2]; // an array of 2 int pointers 
    int (*b)[2]; 
    // pointer to an array of 2 int (invalid until assigned) // 
    int c[2] = {1, 2}; // like b, but statically allocated 

    printf("size of int %ld\n", sizeof(int)); 
    printf("size of array of 2 (int *) a=%ld\n", sizeof(a)); 
    printf("size of ptr to an array of 2 (int) b=%ld\n", sizeof(b)); 
    printf("size of array of 2 (int) c=%ld\n", sizeof(c)); 
    return 0; 
} 

a是2個整數指針的數組,所以不應該是2 * 4 = 8爲什麼sizeof(a)16? (sizeof int是4)

在GCC上測試。

+3

如果您在64位機器上運行,您的指針大小可能爲8個字節,所以2個指針= 16個字節。什麼是你的機器上的sizeof(int *)? – zserge 2012-07-11 09:24:50

回答

10

您可能正在編譯一個指針爲8個字節的64位機器。

int *a[2]是一個2個指針的數組。因此sizeof(a)將返回16
(所以它沒有任何關係與int的大小。)


如果爲32位編譯這一點,你會得到大部分,而不是sizeof(a) == 8

5

在64位機器上,指針通常是8個字節。所以兩個指針數組的大小通常是16個字節。

int *a[2]; // array of two pointers to int 
int (*b)[2]; // pointer to an array of two int 

sizeof a;  // is 2 * 8 bytes on most 64-bit machines 
sizeof b;  // is 1 * 8 bytes on most 64-bit machines 
相關問題