在这个问题,有人建议意见,我应该不会投的结果malloc,即
int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
而不是:
int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
为什么会这样呢?
请使用以下代码:
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?
下面的代码在Windows中执行时返回一个地址,虽然我希望它返回NULL.
int main()
{
char *ptr = NULL;
ptr = malloc(0);
printf("malloc returned = %u\n", ptr);
}
Run Code Online (Sandbox Code Playgroud)
什么可能促使malloc的这种实现?它背后有什么理由吗?
因为,这是一个0字节的内存,我没有尝试写任何数据.但是,这个记忆可以用于任何东西吗?