簡體   English   中英

我該如何解決指針/內存問題?

[英]How can I solve this pointer/memory issue?

我試圖編寫一個程序,要求用戶提供電影信息。 將電影的信息作為結構存儲在向量中,然后使用返回類型為void的2個函數將結果輸出到屏幕。

#include <iostream> 
#include <iomanip> 
#include <vector>
#include <string>
using namespace std;

void make_movie(struct movie *film);
void show_movie(vector <movie> data, int cnt);

struct movie {
    string name;
    string director;
    int year;
    int duration;
};

int main() {

    int count = 0;
    char input;
    vector <movie> record;
    movie *entry = nullptr;

    do {

        make_movie(entry);
        record.push_back(*entry);
        count++;

        cout << endl;
        cout << "Do you have more movie info to enter?\n";
        cout << "Enter y / Y for yes or n / N for no: ";
        cin.ignore();
        cin >> input;
        cout << endl;


    } while (input == 'y' || input == 'Y');

    show_movie(record, record.size());

    return 0;
}

void make_movie(struct movie *film) {

    cout << "Enter the title of the movie: ";
    cin.ignore();
    getline(cin, film -> name);

    cout << "Enter the director's name: ";
    cin.ignore();
    getline(cin, film -> director);

    cout << "Enter the year the movie was created: ";
    cin >> film -> year;

    cout << "Enter the movie length (in minutes): ";
    cin >> film -> duration;

}

void show_movie(vector <movie> data, int cnt) {

    cout << "Here is the info that you entered: " << endl;

    for (int i = 0; i < cnt; i++) {

        cout << "Movie Title: " << data[i].name << endl;
        cout << "Movie Director: " << data[i].director << endl;
        cout << "Movie Year: " << data[i].year << endl;
        cout << "Movie Length: " << data[i].duration << endl;
        cout << endl;
    }
 }

我收到一條錯誤消息,提示我正在嘗試訪問禁止的內存地址。

您需要進行的最少更改是更改:

movie *entry = nullptr;

do {
    make_movie(entry);
    record.push_back(*entry);

至:

movie entry;

do {
    make_movie(&entry);
    record.push_back(entry);

進一步的改進將是:

  • 更改make_movie以通過引用接受參數,則您的程序不使用任何指針,因此不易遭受與指針相關的任何問題。
  • make_movie更改為按值返回,而不是采用引用參數。
  • cin.ignore(); 使用不正確。 您的程序將丟失幾個輸入字符串的第一個字符。 而是刪除所有這些調用,並在make_movie函數的末尾忽略當前行的其余部分。 另外,更改cin >> input; 使用getline

你的蟲子
movie *entry = nullptr;


你有多余的cin.ignore();

    cout << "Enter the title of the movie: ";
//    cin.ignore();
    getline(cin, film -> name);

    cout << "Enter the director's name: ";
//    cin.ignore();
    getline(cin, film -> director);

怎么修

movie main_info;
movie* entry = &main_info;

測試

輸入:

Enter the title of the movie: any_thing  
Enter the director's name: yourself  
Enter the year the movie was created: 2016  
Enter the movie length (in minutes): 120  

Do you have more movie info to enter?  
Enter y / Y for yes or n / N for no: n  

輸出

 Here is the info that you entered: Movie Title: any_thing Movie Director: yourself Movie Year: 2016 Movie Length: 120 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM