采取以下代码:
int *p = malloc(2 * sizeof *p);
p[0] = 10; //Using the two spaces I
p[1] = 20; //allocated with malloc before.
p[2] = 30; //Using another space that I didn't allocate for.
printf("%d", *(p+1)); //Correctly prints 20
printf("%d", *(p+2)); //Also, correctly prints 30
//although I didn't allocate space for it
有了这条线malloc(2 * sizeof *p)
,我正在为两个整数分配空间,对吗?但是,如果我将一个添加int
到第三个位置,我仍然会被正确分配并且可以检索。
所以我的问题是,为什么在使用时指定尺寸malloc
?