CheetahBongos CheetahBongos - 3 months ago 9
C Question

String tokenization strange character output

I am trying to tokenize an array of strings, however, my program keeps printing these strange characters. I believe it has something to do with null-terminating my string. If that is the problem then what can I do to fix it?

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

int main(void)
{
char* s[] = { "12, 34, 56, 78", "82.16, 41.296",
"2, -3, 5, -7, 11, -13, 17, -19",
"9.00009, 90.0009, 900.009, 9000.09, 90000.9" };

char *token = strtok(s, ", ");

while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ", ");
}
return 0;
}


Here is a photo of the output.



Thank you

Answer

You have either messed up your declaration of s (most likely given the remainder of you code), or your have messed up how you declare s and call strtok on s (which is an array-of-pointers-to-char* containing pointers to string literals, as written.)

It appears you actually want char s[] as your declaration. Which would reveal problems with several missing and several extraneous ','s in the initialization. To declare s as an array-of-char initialized holding the list of comma-separated-values, you essentially want

char s[] = { "12, 34, 56, 78, ....,  9000.09, 90000.9" };

There is no requirement that you have only one set of quotes ("..") in the initialization, but each value you seek to tokenize from the string must have a comma that follows (except for the last value). You could declare and initialize s as follows:

char s[] = { "12, 34, 56, 78," "82.16, 41.296,"
              "2, -3, 5, -7, 11, -13, 17, -19,"
              "9.00009, 90.0009, 900.009, 9000.09, 90000.9" };

The remainder of your code works fine in that case, producing the following output:

$ ./bin/strtok_arr
12
34
56
78
82.16
41.296
2
-3
5
-7
11
-13
17
-19
9.00009
90.0009
900.009
9000.09
90000.9

If your intent was to create an array-of-pointers-to-char* (e.g. char *s[]), then you must rework the declaration and the remainder of your code, because (1) you are not passing a character pointer to strtok; and (2) strtok modifies the string it is passed making a call to strtok while passing a string literal just plain wrong -- and guaranteed to SegFault.

Let me know if you have any questions.