如何将char *分配给字符数组?

时间:2013-06-23 11:33:31

标签: c string parsing pointers

我有以下代码:

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;
}

我收到错误:错误:invalid conversion from ‘char*’ to ‘char’ [-fpermissive] 我想将每个单词存储到数组中,有人可以帮忙吗?

1 个答案:

答案 0 :(得分:5)

要存储一整套单词,您需要一个单词数组,或者至少指向一个单词的指针数组。

OP的ch是一个字符数组,而不是指向字符的指针数组。

可能的方法是:

#include <stdlib.h>
#include <stdio.h>

#define WORDS_MAX (50)

int main(void)
{
  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 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 EXIT_SUCCESS;
}