Проблема, указывающая на переменную в структуре в динамической памяти - PullRequest
1 голос
/ 13 октября 2019

Кажется, я не могу ввести значения в структуру, которую я уже объявил. Я не уверен, является ли это синтаксисом или логической ошибкой.

Я уже пытался изменить синтаксис, но всегда получаю ту же ошибку.

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;

1 Ответ

1 голос
/ 13 октября 2019

Прежде всего, в коде есть пара логических ошибок.

  • Абсолютно не нужно иметь две книги с именами 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 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 всех книг в цепочке.

...