【问题标题】:How can I insert value in a char array?如何在 char 数组中插入值?
【发布时间】:2019-11-15 10:04:27
【问题描述】:

我正在尝试创建一个链接列表并将值“Peter”保存在第一个列表元素中。我遇到了 char 数组的问题。我不能在其中插入“彼得”。

    #include <iostream>
    #include <string>
    #include <stdlib.h>

    using namespace std;

    struct ListElement{
    char name[20];
    ListElement* next;

    };

   int main ()
   {

   ListElement* first;
   first = new ListElement;
   first -> name= "Peter"; // Array type 'char [20]' is not assignable


   };

【问题讨论】:

  • 改用strcpy
  • 你不能分配给一个数组,只能复制到它。使用strcpy(如前所述)或使用std::string
  • 你为什么#include &lt;string&gt;然后就不用了?

标签: c++ arrays pointers linked-list


【解决方案1】:

要设置char[] 数组的值,您应该使用strcpystrncpy 函数,例如:

strcpy(first->name, "Peter");

但是,最好使用std::string 类型,您可以直接分配:

struct ListElement{
    std::string name;
    ListElement* next;
};

那么first-&gt;name = "Peter"; 是有效代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-14
    • 2012-03-06
    • 1970-01-01
    • 2017-01-20
    • 2023-03-30
    • 1970-01-01
    • 2017-01-24
    • 2021-12-20
    相关资源
    最近更新 更多