gpt4 book ai didi

c++ - 如何为节点分配名称?我在这里遗漏了什么吗?

转载 作者:太空宇宙 更新时间:2023-11-04 12:20:49 25 4
gpt4 key购买 nike

#include <iostream>

using namespace std;

int main()
{
struct list
{
char name[20];
int age;
double height;
list *next;
};
list *first, *temp, *temp2, *newlist1;
first->next = temp;
temp->next = temp2;
newlist1 = new list;
newlist1->name = "Steve";
newlist1->age = 23;
newlist1->height = 2.3;
newlist1->next = temp2;
temp->next = newlist1;
newlist1->next = temp2;
temp->next = newlist1;
temp2 = newlist1->next;
temp2->next = newlist1->next;
delete temp2;
cout << " Name is: " << newlist1->name << " ";
cout << " Age is: " << newlist1->age << " ";
cout << " Height is: " << newlist1->height;
}

这是将名称值分配给节点的方式吗? ...我试过 strcpy 但它一直说 strcpy 未声明...或其他内容。有人可以告诉我如何将 name[20] char 类型分配到节点上的代码吗?我真的有这个问题:(

最佳答案

strcpy 是标准 C 库的一部分。它的函数声明需要#included 以便编译器知道它是什么。尝试添加 #include <cstring>在文件的开头。

但是,由于您使用的是 C++,我真正的建议是切换到使用 C++ 标准字符串类。使用它更容易、更安全,也更像 C++……为了使用它,#include <string > 然后将您的声明更改为 std::string name;

您很快会遇到的另一个问题是您只分配了 1 个列表对象 (newlist1),但正在引用,例如 first->next什么时候first未初始化。

关于c++ - 如何为节点分配名称?我在这里遗漏了什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5201491/

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