I want to write a programm that converts a string with numbers ("1 2 3") into an integer array. But strtok() doesn't return a value. Why not? My console output is just empty.
Edit: I get no error message.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int* string_to_array(char * string, int * myArray);
int main(void) {
int* myArray = 0;
myArray = (int*) malloc(10 * sizeof(int));
myArray = string_to_array("1 2 3 4", myArray);
printf("result: %d\n", myArray[0]);
printf("result: %d\n", myArray[1]);
return 0;
}
int* string_to_array(char * string, int * myArray){
char delimiter[] = " ";
char *ptr;
char *ptr2;
long ret;
printf("string_to_array() was called.\n");
printf("string is: %s\n", string);
ptr = strtok(string, delimiter); // here is the problem
printf("strtok done; ptr: %s\n", ptr);
int index = 0;
while(ptr != NULL) {
ret = strtol(ptr, &ptr2, 10);
printf("ret: %d\n", ret);
myArray[index] = ret;
ptr = strtok(NULL, delimiter);
index++;
}
return myArray;
}