[英]Segmentation fault (core dumped) copying form array to string
#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]);
}
}
預期的output是這個新世界,但我收到核心轉儲錯誤,任何人都有理由以及如何解決這個問題
這應該有效:
int main()
{
char str[255] = "Hello;thisnewwolrd";
char *ptr = strchr(str, ';') + 1;
char name[255];
strcpy( name, ptr);
printf("%s \r\n", name);
}
您不必重新發明輪子,最好使用標准庫函數進行字符串操作。
您必須分配 memory 來存儲您的字符串副本。 例如: char *name = malloc(255*sizeof(char));
.
並且您必須創建另一個迭代器而不是i
開始填充從索引 0 開始的name
指向的 memory 空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.