gpt4 book ai didi

c - 如何将 char* 分配给数组变量

转载 作者:行者123 更新时间:2023-12-02 01:24:46 25 4
gpt4 key购买 nike

我最近开始用 C 编写代码,并且从中获得了很多乐趣。但是我遇到了一个小问题,我已经尝试了所有我能想到的解决方案但没有成功。如何将 char* 变量分配给数组?

例子

int main()
{
char* sentence = "Hello World";

//sentence gets altered...

char words[] = sentence;

//code logic here...

return 0;
}

这当然会给我一个错误。非常感谢回答。

最佳答案

  1. 你需要给数组words一个长度

    char words[100]; // For example
  2. 使用strncpy复制内容

     strncpy(words, sentence, 100);
  3. 以防万一字符串sentence太长时添加一个空字符

     words[99] = 0;

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

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