所以,我是C的新手.
我面临着困惑.如果我有,
int a;
Run Code Online (Sandbox Code Playgroud)
在这里,我不为手动分配内存.它由编译器自动完成.
现在,如果以类似的方式,如果我这样做,
char * a;
Run Code Online (Sandbox Code Playgroud)
我需要为指针分配内存吗?
其次,我制作了这段代码,
#include <stdio.h>
int main (void)
{
int *s=NULL;
*s=100;
printf("%d\n",*s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
为什么我在这段代码中出现seg错误?是因为我没有为指针分配内存吗?但正如上面提到的问题,我可以简单地声明它,而无需手动分配内存.
PS:我是新手,我在这方面面临困惑.如果这是一个糟糕的问题,请保管我.谢谢.
编辑:我在SO上阅读了malloc的帖子.
http://stackoverflow.com/questions/1963780/when-should-i-use-malloc-in-c-and-when-dont-i
Run Code Online (Sandbox Code Playgroud)
它并没有真正解决我的怀疑.
您不需要为指针本身分配内存.这是自动的,就像int你的第一个代码片段一样.
你需要分配的是指针指向的内存,你需要初始化指针指向那个.
由于您没有分配任何空间,因此*s=赋值是未定义的行为.s本身(指针)被分配,并初始化为NULL.您不能取消引用(*s- 查看指针指向的内容)空指针.
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int *s = NULL; // s is created as a null pointer, doesn't point to any memory
s = malloc(sizeof(int)); // allocate one int's worth of memory
*s = 100; // store the int value 100 in that allocated memory
printf("%d\n",*s); // read the memory back
free(s); // release the memory
// (you can't dereference s after this without
// making it point to valid memory first)
return 0;
}
Run Code Online (Sandbox Code Playgroud)