gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:18:51 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,向用户询问电影信息。将电影的信息作为结构存储在 vector 中,然后使用返回类型为 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

关于c++ - 我该如何解决这个指针/内存问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41972465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com