ない他の人がコメントで述べたように、セグメンテーションフォールトが
ある場合、あなたはポインタ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;
各アレイではありません。 strtokを使うとそれもやらなくてはなりません。 [mcve]を提供すると、コードを修正できる可能性があります。それは好きではありません。 –
このようなことを意味しますか?strptr [strcnt] = malloc(sizeof(char *)); ?私はこれをしましたが、それはまだ助けません。 – user691197
'strptr [strcnt] = malloc(real_string_size + 1)'が良いでしょう。 –