我想從現有的字符串中提取子字符串,但它引發了分段錯誤錯誤。它在早上執行得很好,但我不知道爲什麼它現在給出了seg錯誤請別人幫我。子字符串C程序中的分段錯誤
#include <stdio.h>
#include <string.h>
int main()
{
char str[] ="1017122,1,10,?,1,1";
char * pch,*pch1;
FILE *fp;
char *str1,*str2;
int noofattr=0;
int strlen1;
/*if(remove("abc.txt") != 0)
perror("The file is successfully deleted.\n");
else
printf("Error in deleting the file.\n");
*/
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str,",");
while(pch!=NULL)
{
if(strcmp(pch,"?")!=0)
{
strcat(str1,pch);
strcat(str1,",");
}
else
{
strcat(str1,pch);
strcat(str1,",");
}
pch = strtok (NULL,",");
noofattr++;
}
strlen1=strlen(str1);
//memcpy(str2,&str1,strlen1-1);
// strncpy(str1,str1+0,strlen1-1);
printf("\nThe formatted string is %s and its length is %d\n",str1,strlen1);
printf("\nThe total no. of attributes except SCN are %d\n",noofattr);
return 0;
}
你有沒有試過通過gdb運行它?調試器對於解決這樣的問題是非常寶貴的。 – sonicwave
不..不知道它...它是Windows調試器嗎? – Teja
當得到分段錯誤或任何其他崩潰時,您的第一反應應該是在調試器中運行您的程序。它會幫助你找到崩潰的位置,並讓你檢查變量以幫助你理解崩潰的原因。 –