我尝试使用 strcpy 将字符串处理为指针。它会导致分段错误。任何原因。
#include <stdio.h>
#include <string.h>
int main()
{
char *str=NULL;
strcpy(str,"C-DAC");
printf("%s\n",str);
return 1;
}
你的字符串指向哪里?无处!
这就是为什么你有分段错误。您必须将堆栈上的变量分配为数组或将其定义为指针,然后使用malloc
. 使用时malloc
,不要忘记包含“stdlib.h”
要么这样做:
char str[6];
strcpy(str,"C-DAC");
或者
char *str=malloc(sizeof(*str) * 6);
strcpy(str,"C-DAC");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句