簡體   English   中英

分段錯誤 - 拆分字符串

[英]Segmentation fault - split string

你能幫我修復下面的代碼嗎? 不確定分段錯誤在哪里。

 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;

 }

請忽略我糟糕的編碼:)

PS:我知道使用 strtok() 可以輕松拆分。

不確定分段錯誤在哪里

正如其他人在評論中提到的那樣,您沒有為指針strptr[0]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;

這是一個關於如何初始化指向指針的指針的問題


然后,在使用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)
}

不要忘記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);

總而言之,您的代碼將是這樣的:

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