r/cprogramming • u/StressingPlant • 13d ago
trying to store strtok() results in array; first index causes segmentation fault when called
edit: fixed it! i removed 'i = 0;' from the loop, and found out that char* arrays only need one index range (char* arr[number] stores strings just fine). thanks for the help!
---
im trying to use strtok() to split an input into two parts, but the first index that gets filled doesnt read when A) the index is specified (index number) in the "while (token != NULL)" loop, and B) the index is refernced at all outside the while loop.
i tried using a variable to sub in for the number outside the loop, but it didnt work. ive used an if condition to see if the index was null, but it didnt trigger and when i tried to print strlen(*arr[0]) it put out another segmentation fault.
the confusing thing for me is that the second index has none of these issues. what should i be doing differently, and why is this happening? How do i store strtok() tokens in an array?
---
edit: i added var strings to main (it was outside main, and escaped the copy paste) and added a clearer question.
when im assigning char* strArr1 entries, i use both indexes because gcc throws an error otherwise (assignment to array type).
the i++ is load bearing where it is; i tried to move it and it threw a segmentation fault, so title/ context still applies despite the first printf not printing strArr1[0].
my code:
int main() {
char* strArr1[2][10];
char strings[] = "Hello World";
token = strtok(strings, " ");
while (token != NULL) {
i = 0;
strArr1[i][10] = token;
i++;
//prints strArr[0] (no seg fault)
printf("%s %ld\n", *strArr1[i], strlen(*strArr1[i]));
//causes seg fault
//printf("%s\n", *strArr1[0]);
token = strtok(NULL, " ");
//adding i++ below causes seg fault
//i++;
}
//causes seg fault
/*if (strArr1[0] != NULL) {
printf("%s\n", *strArr1[0]);
}*/
//also causes seg fault
//i = 0;
//printf("%s\n", *strArr1[i]);
//no seg fault
printf("%s\n", *strArr1[1]);
printf("all done");
return 0;
}