相关疑难解决方法(0)

为什么在C中使用malloc时指定大小?

请使用以下代码:

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

c malloc memory-management

21
推荐指数
4
解决办法
3256
查看次数

标签 统计

c ×1

malloc ×1

memory-management ×1