0

我正在尝试从现有字符串中提取子字符串。但是它抛出了分段错误错误。它在早上执行得很好,但我不知道为什么它现在给出了段错误。请有人帮助我。

#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;
}
4

2 回答 2

1

str1指向内存中的一个随机位置,您必须(是的,必须)将其设置为一个足够大的缓冲区,以便在尝试 a 之前保存最终结果strcat

于 2012-09-12T06:10:27.450 回答
0

str1没有分配,当然它会出现段错误。

于 2012-09-12T06:12:01.490 回答