我只是想用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