为什么下面的代码会产生分段错误

普拉奈·萨拉伊瓦拉

我尝试使用 strcpy 将字符串处理为指针。它会导致分段错误。任何原因。

#include <stdio.h>
#include <string.h>
int main()
{   
    char *str=NULL;
    strcpy(str,"C-DAC");
    printf("%s\n",str); 
    return 1;
}
tilz0R

你的字符串指向哪里?无处!

这就是为什么你有分段错误。您必须将堆栈上的变量分配为数组或将其定义为指针,然后使用malloc. 使用时malloc,不要忘记包含“stdlib.h”

要么这样做:

char str[6];
strcpy(str,"C-DAC");

或者

char *str=malloc(sizeof(*str) * 6);
strcpy(str,"C-DAC");

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章