Anu*_*ana 1 c pointers segmentation-fault
我Segmentation fault (core dumped)在下面的代码中收到错误.
请告诉我哪里出错了?
#include "string.h"
int main(){
char *str=NULL;
strcpy(str,"something");
printf("%s",str);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在浏览一个网站,在那里我看到了这个问题,并试图编译代码.它说预期输出应为(null).这是链接cquestions.com/2010/10/c-interview-questions-and-answers.html第13个问题最后一个例子
str在将字符串复制到它之前,您需要分配内存.
char *str = malloc(10) // Length of string "Something" + 1
Run Code Online (Sandbox Code Playgroud)
需要注意的是后分配NULL到str,它指向无处作为C-FAQ说:
[...]空指针明确指出无处; 它不是任何对象或功能的地址.
如果str不是任何对象的地址,那怎样才能将任何东西复制到它?