简体   繁体   English

分段错误 - 拆分字符串

[英]Segmentation fault - split string

Can you please help me with fixing below code.你能帮我修复下面的代码吗? Not sure where the segmentation fault is.不确定分段错误在哪里。

 char str[] = "00ab00,00cd00";
 char **strptr;
 int i;

 strptr = malloc(sizeof(char*) * 2);

 strcnt = 0;
 int j=0;
 for(i=0;i<sizeof(str);i++) {

   char c = *(str+i);
   printf("%c", c);

   if(c==',') {
     strcnt++;
     j=0;
   }

   strptr[strcnt][j++] = c;

 }

Please ignore my poor coding :)请忽略我糟糕的编码:)

PS: I know its possible to split using strtok() easily. PS:我知道使用 strtok() 可以轻松拆分。

Not sure where the segmentation fault is不确定分段错误在哪里

As others have mentioned in the comments, you are not assigning memory to the pointers strptr[0] and strptr[1] but, you are trying to access them.正如其他人在评论中提到的那样,您没有为指针strptr[0]strptr[1]分配内存,而是尝试访问它们。 This leads to segmentation fault.这会导致分段错误。

Use a for loop to initially assign memory to strptr[0] and strptr[1]使用for循环最初为strptr[0]strptr[1]分配内存

strptr = malloc(sizeof(char*) * 2);
for(i = 0; i < 2; i++) //here, initialise each to 1 byte
{
    strptr[i] = malloc(1); 
}
strcnt = 0;

Here's a question on how to initialise a pointer to a pointer .这是一个关于如何初始化指向指针的指针的问题


then, resize them at each step as you add additional character using the realloc() function.然后,在使用realloc()函数添加其他字符时,在每一步调整它们的大小。

for(i = 0, j = 0; i < sizeof(str); i++) 
{

   strptr[strcnt] = realloc(strptr[strcnt], j + 2); 
   //here, you resize each time to provide space for additional character using realloc() 
   char c = *(str + i);

   printf("%c", c);

   if(c == ',') 
   {
     ++strcnt;
     j=0;
     continue; //use a continue here
   }

   strptr[strcnt][j] = c;
   strptr[strcnt][++j] = '\0'; 
   //to provide null terminating character at the end of string (updated to next position at every iteration)
}

don't forget to free() the allocated memory不要忘记free()分配的内存

for( i=0; i<2; i++)
{
    printf("%s\n", strptr[i]); //just to display the string before `free`ing
    free(strptr[i]);
}

free(strptr);

Altogether your code would be something like this:总而言之,您的代码将是这样的:

char str[] = "00ab00,00cd00";
char **strptr;

int i, j;
int strcnt; 

strptr = malloc(sizeof(char*) * 2);
for(i = 0; i < 2; i++)
{
    strptr[i] = malloc(1); 
}
strcnt = 0;


for(i = 0, j = 0; i < sizeof(str); i++) 
{

   strptr[strcnt] = realloc(strptr[strcnt], j + 2); 
   char c = *(str + i);

   printf("%c", c);

   if(c == ',') 
   {
     ++strcnt;
     j=0;
     continue;
   }

   strptr[strcnt][j] = c;
   strptr[strcnt][++j] = '\0';
}

for( i=0; i<2; i++)
{
    printf("%s\n", strptr[i]);
    free(strptr[i]);
}

free(strptr);

return 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM