How to assign char * to a character array?

I have the following code:

int main(){ char sentence[] = "my name is john"; int i=0; char ch[50]; for (char* word = strtok(sentence," "); word != NULL; word = strtok(NULL, " ")) { // put word into array // *ch=word; ch[i]=word; printf("%s \n",ch[i]); i++; //Above commeted part does not work, how to put word into character array ch } return 0; } 

I get the error: error: invalid conversion from 'char*' to 'char' [-fpermissive] I want to store each word in an array, can anyone help?

+4
source share
1 answer

To store a whole set of words, you need an array of words, or at least an array of pointers pointing to each word.

OP ch is an array of characters, not an array of pointers to characters.

Possible approach:

 int main() { char sentence[] = "my name is john"; int i = 0; char * ch[50] = {0}; /* This stores references to 50 words. */ char * word = strtok(sentence, " "); /* Using the while construct, keeps the program from running into undefined behaviour (most propably crashing) in case the first call to strtop() wold return NULL. */ while ((NULL != word) && (50 > i)) { ch[i] = strdup(word); /* Creates a copy of the word found and stores it reference in ch[i]. This copy should to be free()ed if not used anymore. */ printf("%s\n", ch[i]); i++; word = strtok(NULL, " ") } return 0; } 
+4
source

Source: https://habr.com/ru/post/1487708/


All Articles