我该如何解决这个指针/内存问题?

时间:2017-02-01 05:24:42

标签: c++ function pointers out-of-memory

我尝试编写一个程序,要求用户提供电影信息。将影片的信息作为结构存储在向量中,然后将结果输出到具有返回类型为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;
    }
 }

我收到一条错误消息,表示我正在尝试访问禁止的内存地址。

2 个答案:

答案 0 :(得分:1)

您需要做的最少量更改是:

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

答案 1 :(得分:0)

你的错误
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;

<强>测试

intput:

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