I am new to C language and hoping to get a good understanding char array assignment coming from Java background. I use stringTok()
to split the local sentence[]
array into individual array word and want to assign that word to char ** tokens
that was being passed in. I received the following output:
value of i:4
len:1 ,
len:1 ,
len:6 ,8?k
len:0 ,
Some have values (the assigned values are gibberish) and some don't. I initially thought that I had to allocate memory to each char in the character array. However, that didn't seem to work either. So, I suppose I must have done something wrong then. I have also tried using tokens[4][10]
instead of char ** tokens
and did not make any difference either. So, I was stuck in this for quite a while.
#include <string.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void stringTok(char** tokens)
{
int i = 0;
char sentence[] = "jake is really cool.";
char *word = strtok(sentence, " .");
while (word != NULL)
{
//printf("%s\n", word);
tokens[i++] = word;
word = strtok(NULL, " .");
}
printf("value of i:%d\n", i);
tokens[i] = NULL;
}
int main()
{
char **cmdArr = calloc(5, sizeof(char*));
for (int i = 0; i < 5; i++)
cmdArr[i] = (char*)calloc(10, sizeof(char));
stringTok(cmdArr);
for(int i = 0; i < 4; i++)
{
printf("len:%ld ,", strlen(cmdArr[i]));
printf("%s\n", cmdArr[i]);
}
return 0;
}