How do I assign the strtok return to an array of strings?

0

Well, I was testing the strtok function, but it's giving me this problem of "segmentation failure (recorded core image)".

Before I tried to strPtr [i] = strtok (str1, str2); but gave this error:

  

"error: assignment to expression with array type error"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void)
{
char str1[] = "Teste de funcao que separa string em tokens";
char str2[] = " ";
char strPtr[10][10];


char *aux;
int i;
aux = strtok (str1, str2);
strcpy (strPtr[0], aux);
for (i = 1; strPtr[i] != NULL; i++)
{
    aux = strtok (NULL, str2);
    strcpy (strPtr[i], aux);
}

for (i = 0; i < 10; i++)
{
    puts(strPtr[i]);
}

return 0;

}
    
asked by anonymous 28.12.2017 / 23:04

1 answer

1

According to the Standard C Library documentation, Section ¶7.1.4 (translation done by me)

  

Each of the following statements applies unless   explicitly stated otherwise in the detailed descriptions that   follows: if an argument to a function has an invalid value   (such as [...] a null pointer [...]) ... the behavior is   indefinite.

Therefore, when aux has the value NULL , you will find undefined behavior. This will happen because your loop of repetition does not verify such a situation.

I suggest you modify your loop that feeds your array from strings . Something like

for (char *aux = strtok(str1, str2); aux != NULL; aux = strtok(NULL, str2))
{
  ...
}

See working here .

    
29.12.2017 / 00:02