How to assign the return of Strtok to an array of strings?

Asked

Viewed 150 times

0

Guys, I was testing the function strtok only it is giving this problem of "Segmentation failure (recorded core image)".

Before I tried to do strPtr [i] = strtok (str1, str2); but I made that mistake:

"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;

}

1 answer

1


According to C Standard Library documentation, Section 7.1.4 (translation made by me)

Each of the following statements applies unless it is explicitly stated otherwise in the detailed descriptions that If an argument for a function has an invalid value (as [...] a null pointer [...]) [...] the behavior is undefined.

Therefore, when aux hold the value NULL, you will encounter an undefined behavior. This will happen because your repeat loop does not check such a situation.

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

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

See working here.

  • 1

    I would say even more: independent of the behaviour of the functions strcpy and strtok, that loop in the uninitialized variable is destined to always impact on that error, because almost always the memory region will contain garbage and will never reach this strPtr[i] == NULL, therefore every operation made on strPtr[i] is subject to this problem

  • Thank you, it worked now! You could explain to me why when I declare char *aux outside the for she gives this Warning "assignment makes integer from Pointer without a cast" ?

  • @Weird Thiagorizzi, I moved the statement out of the for and compiled without problems. Are sure that this was your only change?

  • @Strange merchant that I went to test and worked now, strange things happen in kkkk programming

Browser other questions tagged

You are not signed in. Login or sign up in order to post.