2016-09-24 4 views
-2

以下のコードを修正してもらえますか?セグメンテーションフォルトがどこにあるかわからない。セグメンテーションフォルト - 分割文字列

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()を使用して分割するために、その可能性を知っているし。

+0

各アレイではありません。 strtokを使うとそれもやらなくてはなりません。 [mcve]を提供すると、コードを修正できる可能性があります。それは好きではありません。 –

+0

このようなことを意味しますか?strptr [strcnt] = malloc(sizeof(char *)); ?私はこれをしましたが、それはまだ助けません。 – user691197

+1

'strptr [strcnt] = malloc(real_string_size + 1)'が良いでしょう。 –

答えて

0

ない他の人がコメントで述べたように、セグメンテーションフォールトが

ある場合、あなたはポインタstrptr[0]strptr[1]にメモリを割り当てるされるのではなく、あなたがそれらにアクセスしようとしていることを確認。これによりセグメンテーション・フォルトが発生します。

は当初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; 

にメモリを割り当てることがforループを使用して、ここでhow to initialise a pointer to a pointerの質問ですね。あなたが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) 
} 

割り当てられたメモリ

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

free(strptr); 

を完全にあなたのコードはこのようなものになるだろうfree()することを忘れないでください:あなたは、配列を割り当てている

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;