将表单数组复制到字符串时出现分段错误(堆芯转储) #包括 #包括 int main() { char str[255]=“你好;Thisnewolrd”; int i=0; while(str[i]!=';') { i++; } i++; char*name=NULL; while(str[i]!=NULL) { 名称[i]=str[i]; i++; printf(“%c\r\n”,名称[i]); } }
预期输出是thisnewolrdthisnewolrd,但我得到了内核转储错误将表单数组复制到字符串时出现分段错误(堆芯转储) #包括 #包括 int main() { char str[255]=“你好;Thisnewolrd”; int i=0; while(str[i]!=';') { i++; } i++; char*name=NULL; while(str[i]!=NULL) { 名称[i]=str[i]; i++; printf(“%c\r\n”,名称[i]); } },c,segmentation-fault,coredump,C,Segmentation Fault,Coredump,预期输出是thisnewolrdthisnewolrd,但我得到了内核转储错误 任何人都有理由和方法来解决这个问题,你必须分配内存来存储你的字符串副本。例如:char*name=malloc(255*sizeof(char)) 您必须创建另一个迭代器,而不是i,以开始填充name从索引0开始指向的内存空间。这应该可以: #include <string.h> #include <stdio.h> int main() { char str[255] = "Hello;
任何人都有理由和方法来解决这个问题,你必须分配内存来存储你的字符串副本。例如:
char*name=malloc(255*sizeof(char))代码>
您必须创建另一个迭代器,而不是i
,以开始填充name
从索引0开始指向的内存空间。这应该可以:
#include <string.h>
#include <stdio.h>
int main()
{
char str[255] = "Hello;thisnewwolrd";
int i =0;
while(str[i] != ';')
{
i++;
}
i++;
char *name = NULL;
while(str[i] != NULL)
{
name[i] = str[i];
i++;
printf("%c \r\n",name[i]);
}
}
你不必重新发明轮子,使用标准库函数进行字符串操作会更好。你没有为name
分配内存,你忘了提到i
@ArdentCoder的问题什么问题?@Welgrivi!=0
在第一个循环之后,因此name
的开头变成了垃圾,如果我不想使用标准函数的话otherway@ganeshb你在一个10行长的程序中犯了几个严重错误,结果是“分段错误”,我认为使用标准函数是你的安全赌注,直到你变得更好并且能够编写好代码。如果你不停地从自行车上摔下来,使用训练轮没有什么丢脸的。好的,有什么建议或链接可以学习和改进我的代码吗?因为我是新来的C@ganeshb任何关于C的入门书都可以。我也建议推荐学习C++,因为它们非常接近,并且有很多概念。并且请远离那些带有编码难题的网站,比如HakrAKE,因为这些站点鼓励写坏代码。如果你提供了一些有助于完整的网站的链接,你有没有链接的书或名字或者一些站点C和C++?
int main()
{
char str[255] = "Hello;thisnewwolrd";
char *ptr = strchr(str, ';') + 1;
char name[255];
strcpy( name, ptr);
printf("%s \r\n", name);
}