This C program splits the string "1 2 3 4 5 6 7 8 9 10" into tokens, stores these in buf, and prints the contents of buf.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/* Fills an array with pointers to the tokens of the given string.
* string: A null-terminated char*
* buf: A buffer to be filled with pointers to each token.
*/
void get_tokens(char * string, char ** buf) {
char tmp[100];
strncpy(tmp, string, 100);
char * tok = strtok(tmp, " \n");
int i = 0;
while (tok != NULL) {
buf[i] = tok;
tok = strtok(NULL, " \n");
i++;
}
}
int main() {
char ** buf = malloc(10 * sizeof(char*));
char * string = "1 2 3 4 5 6 7 8 9 10";
get_tokens(string, buf);
int i;
for (i = 0; i < 10; i++) {
printf(" %s\n", buf[i]);
}
}
The output:
1
2
3
4
s�c8
�c8
8
9
10
Why is my output being mangled?
tmpbeing out of scope after returning fromget_tokens.char tmp[100];is local variable. Address of that part invalid at out of scope.char * tok = strtok(tmp, " \n"); buf[i] = tok;.tokpoints to a position withintmp.\0and returns a pointer to the start of each token within tmp.