Не знаете, где ошибка сегментации
Как уже упоминалось в комментариях, вы не назначая память указателей 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;
Вот вопрос, на 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)
}
не забудьте 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;
вы выделения массива или массивы, но не каждый массив. С strtok вам тоже придется это сделать. если вы предоставите [mcve], мы сможем исправить ваш код. но не так. –
Вы имеете в виду что-то вроде этого - strptr [strcnt] = malloc (sizeof (char *)); ? Я сделал это, но он по-прежнему не помогает. – user691197
'strptr [strcnt] = malloc (real_string_size + 1)' будет лучше; –