指向动态内存中结构中的变量时出现问题
Problem pointing to a variable in a structure in dynamic memory
我似乎无法将值输入到我已经声明的结构中。我不确定这是语法错误还是逻辑错误。
我已经尝试更改语法,但总是以相同的错误告终。
struct Book{
string title;
Book* next;
};
Book bookName;
Book author;
Book* add_node(Book* in_root){
cout <<"Enter Book name n";
cin >> bookName.title;
cout << "Enter author name n";
cin >> author;
author = new Book();
Book -> Book.next = author;
}
在代码的这一部分中遇到错误:
cout << "Enter author name n";
cin >> author;
author = new Book();
Book -> Book.next = author;
首先,代码中有几个逻辑错误。
- 绝对没有必要有两本书命名为
bookName
和author
,除非我误解了它们的目的。 Book ->
和Book.next
是无效逻辑,因为您告诉它对数据类型进行操作Book
,而不是类型Book
的对象。
您可能想要的代码应如下所示:
#include <iostream>
#include <string>
using namespace std;
struct Book{
string title;
string author_name; // You potentially wanted this?
Book* next;
};
// This function assumes that `current_node->next` is `nullptr`
// The reasons for this is that making it handle such cases might be too difficult for you yet.
Book* add_node(Book* current_book){
if(current_book == nullptr){
cout << "Cannot link a new book to an non-existant book!n";
return nullptr;
}
Book* new_book = new Book();
cout <<"Enter the book namen";
cin >> new_book->title;
cout << "Enter the author namen";
cin >> new_book->author_name;
new_book->next = nullptr;
current_book->next = new_book;
return new_book;
}
int main(){
Book* book = new Book();
book->next = nullptr;
cout <<"Enter the name of the first bookn";
cin >> book->title;
cout << "Enter the name of the first book's authorn";
cin >> book->author_name;
add_node(add_node(book));
return 0;
}
我没有让函数在current_book->next != nullptr
时处理情况的原因是因为它需要使用指向指针的指针。 如果你对它感兴趣,这里是:
Book* add_node_v2(Book* current_book){
if(current_book == nullptr){
cout << "Cannot link a new book to an non-existant book!n";
return nullptr;
}
Book* new_book = new Book();
cout <<"Enter the book namen";
cin >> new_book->title;
cout << "Enter the author namen";
cin >> new_book->author_name;
new_book->next = nullptr;
// Move to the last book in the chain
Book** ptr_to_next = ¤t_book->next;
while(*ptr_to_next != nullptr){
ptr_to_next = &(*ptr_to_next)->next;
}
*ptr_to_next = new_book;
return new_book;
}
请记住,您最终将不得不delete
链中的所有书籍。
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++理解计算字符变量的问题
- 在通知提升间处理条件变量时未按住锁会导致问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 将十六进制值设置为用于填充的字符变量时出现问题
- 初学者问题:如何访问此变量?
- 关于仅正确使用二传手和变量的问题
- 为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 在 for 循环中更新两个变量时遇到问题C++
- 为<vtkDataArray> VTK 非结构化网格声明 vtkSmartPointer 类型的变量时出现问题
- 模板类编译问题与 typedef 变量
- 简单的问题 - 如何从单独的"结构"内的'class'访问变量?
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 初学者问题:C++指针/地址 - 和变量之后不是以前?
- 关于读取有效 c++ 第 4 项(将非局部静态变量替换为局部静态变量)的问题
- 我有几个关于参考变量的问题
- 面临在 if 语句之外打印变量数据的问题 完成使用 Qt 编程
- OpenCV C++ Mat 类行和列 - 它们是成员变量(和相关问题)吗?
- 指向动态内存中结构中的变量时出现问题