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

问题描述 投票:1回答:1

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

我已经尝试过更改语法,但是总是以相同的错误结尾。

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;
c++ dynamic struct heap dynamic-memory-allocation
1个回答
0
投票

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

  • 除非我误解了它们的目的,否则绝对没有两本名为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;
}

请记住,您最终将不得不delete连锁中的所有书籍。

© www.soinside.com 2019 - 2024. All rights reserved.