【问题标题】:How to assign char * to character array?如何将 char * 分配给字符数组?
【发布时间】:2013-06-23 11:33:31
【问题描述】:

我有以下代码:

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] 我想将每个单词存储到数组中,有人可以帮忙吗?

【问题讨论】:

  • strcpy 是您所需要的。或者,从你的使用方式来看,可能是char *ch[50];?
  • 你有四个单词,但只有一个数组。因此,当您说要将每个单词“存储到字符数组中”时,您到底是什么意思?
  • 是的 strcpy 在这里会有所帮助,我使用 strcpy(ch[i], word);这也给出了同样的错误
  • 实际上我想将每个单词存储为数组元素并传递整个数组以匹配单词!
  • @abelenky:它给出了分段错误(核心转储)错误

标签: c string parsing pointers


【解决方案1】:

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

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

一种可能的方法是:

#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\n", ch[i]);
    i++;

    word = strtok(NULL, " ")
  }

  return result;
}

【讨论】:

  • 非常感谢,有人请给这个答案投票,我没有足够的分数来投票:(
猜你喜欢
  • 2015-06-25
  • 1970-01-01
  • 1970-01-01
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 2014-06-08
  • 2012-10-16
  • 2012-05-03
相关资源
最近更新 更多