c++ - 指向动态内存结构中的变量的问题

标签 c++ struct dynamic heap-memory dynamic-memory-allocation

我似乎无法将值输入到我已经声明的结构中。我不确定这是语法错误还是逻辑错误。

我已经尝试过更改语法,但总是以同样的错误告终。

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;

最佳答案

首先,代码中有几个逻辑错误。

  • 绝对没有必要将两本书命名为 bookNameauthor 除非我误解了它们的目的。
  • 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 name\n";
    cin >> new_book->title;

    cout << "Enter the author name\n";
    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 book\n";
    cin >> book->title;

    cout << "Enter the name of the first book's author\n";
    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 name\n";
    cin >> new_book->title;

    cout << "Enter the author name\n";
    cin >> new_book->author_name;

    new_book->next = nullptr;

    // Move to the last book in the chain
    Book** ptr_to_next = &current_book->next;
    while(*ptr_to_next != nullptr){
        ptr_to_next = &(*ptr_to_next)->next; 
    }

    *ptr_to_next = new_book;
    return new_book;
}

请记住,您最终必须删除链中的所有图书。

关于c++ - 指向动态内存结构中的变量的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58364661/

相关文章:

c++ - 至少一个字符的正则表达式

c++ - 训练 NN 计算 atan2(y, x)

c++ - 在 Cython 中使用 C++ 复杂函数

python - 访问具有动态名称的变量值

c++ - 避免调用默认、移动和复制构造函数

c - C 从指向结构体第二个成员的指针获取指向结构体的指针是否合法?

c - 为什么我总是丢失结构成员的值?

java - 以编程方式动态导入

javascript - JavaScript 数组在物理内存中是如何表示的?

C 编译错误 : array type has incomplete element type