我只是想用C 動態聲明數組的代碼如下:爲什麼我會丟失字節?
int maxSize = 3;
int *answer;
answer = malloc(maxSize * sizeof(int));
printf("this is max size: %d\n", maxSize);
printf("this is the mult result: %d\n", maxSize * sizeof(int));
printf("size of answer in bytes: %d\n", sizeof(answer));
printf("size of the answer array: %d\n", sizeof(answer)/sizeof(answer[0]));
打印結果給我:
this is max size: 3
this is the mult result: 12
size of answer in bytes: 8
size of the answer array: 2
我不認爲這是一個架構的東西(相反我沒有經驗),但我在Macbook Pro上運行它。
我不明白爲什麼malloc只爲整數數組分配8個字節而不是12個字節。
你爲什麼會分配12個字節? –
你給maxSize提供了一個值嗎?我沒看到它。 – DigitalNinja
@George Stocker因爲我的機器的大小和int是4個字節。由於'maxSize'是3個字節,所以我希望爲長度爲3的整數分配足夠的內存。 – FSB