请使用以下代码:
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
Run Code Online (Sandbox Code Playgroud)
malloc(2 * sizeof *p)我用这条线为两个整数分配空间,对吧?但是如果我添加int到第三个位置,我仍然可以正确分配并可检索.
所以我的问题是,为什么在使用时指定尺寸malloc?