2012-07-11 1 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입니까? (int의 크기는 4입니다.)

GCC에서 테스트되었습니다.

+3

64 비트 컴퓨터에서 실행중인 경우 포인터 크기는 8 바이트이므로 2 포인터 = 16 바이트가 될 수 있습니다. 컴퓨터에서 sizeof (int *) 란 무엇입니까? – zserge

답변

10

아마도 포인터가 8 바이트 인 64 비트 시스템에서 컴파일하고있을 것입니다.

int *a[2]은 2 개의 포인터의 배열입니다. 32 비트이 컴파일 따라서 sizeof(a)이 (그래서이 int의 크기와는 아무 상관이 없습니다.)


16
을 반환, 당신은 대부분 대신 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