Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

c - 如何将char *分配给字符数组?(How to assign char * to character array?)

I have 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 
",ch[i]);
        i++;

        //Above commeted part does not work, how to put word into character array ch
    }
    return 0;
}

I am getting error: error: invalid conversion from 'char*' to 'char' [-fpermissive] I want to store each word into array, can someone help?

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

  ask by translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...