To store a whole set of words you need an array of words, or at least an array of pointers pointing to a word each.
(要存储整个单词集,您需要一个单词数组,或者至少每个指向一个单词的指针数组。)
The OP's ch
is an array of characters and not an array of pointers to characters.
(OP的ch
是一个字符数组,而不是一个指向字符的指针数组。)
A possible approach would be:
(一种可能的方法是:)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define WORDS_MAX (50)
int main(void)
{
int result = EXIT_SUCCESS;
char sentence[] = "my name is john";
char * ch[WORDS_MAX] = {0}; /* This stores references to 50 words. */
char * word = strtok(sentence, " "); /* Using the while construct,
keeps the program from running
into undefined behaviour (most
probably crashing) in case the
first call to strtok() would
return NULL. */
size_t i = 0;
while ((NULL != word) && (WORDS_MAX > i))
{
ch[i] = strdup(word); /* Creates a copy of the word found and stores
it's address in ch[i]. This copy should
be free()ed if not used any more. */
if (NULL == ch[i])
{
perror("strdup() failed");
result = EXIT_FAILURE;
break;
}
printf("%s
", ch[i]);
i++;
word = strtok(NULL, " ")
}
return result;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…