gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:26:52 26 4
gpt4 key购买 nike

我有以下代码:

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

我收到错误:错误:从“char*”到“char”的无效转换 [-fpermissive]我想将每个单词存储到数组中,有人可以帮忙吗?

最佳答案

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

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

关于c - 如何将 char * 分配给字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17260327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com