c++ - 数组和指针有问题

标签 c++ arrays pointers structure

我目前正在阅读一本书来刷新我对 C++ 的内存。我所在的章节与动态内存分配有关。我在做一个练习题,但我在弄清楚我的程序出了什么问题时遇到了一些麻烦。问题是

“编写一个程序,让用户记录他们最后一次与每个 friend 交谈的时间。用户应该能够添加新 friend (想加多少就加多少!)并存储他们上次交谈的天数。与每个 friend 交谈。让用户更新此值(但不要让他们输入负值等虚假数字)。可以显示按 friend 姓名排序的列表每个 friend 。”

现在我只是想让程序正确存储用户的输入。

它在我输入 5 个 friend 后崩溃,所以我猜它是在数组上写入,但 Resize 函数应该会处理这个问题。

他是我的密码

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

struct Friend
{
  string friends;
  int days;
};

Friend Resize(Friend* p_array, int* size_of_array);

int main()
{
  struct Friend f;
  int quit = 1;
  int array_size = 5;
  int number_of_friends = 0;
  Friend *p_array = new Friend [array_size];

  while(quit != 0)
  {
      cout << "Enter a friends name.\n";
      cin >> f.friends;
      cout << "Enter the number of days sence you last saw them.\n";
      cin >> f.days;
      cout << "Enter '0' to quit the program.\n";
      cin >> quit;

      if(array_size == number_of_friends)
      {
        Resize(p_array, &array_size);
      }

      p_array[number_of_friends] = f;

      number_of_friends++;
  }

  //print the array
  cout << endl;
  for(int i = 0; i < sizeof(p_array); i++)
  {
    cout << p_array[i].friends << " " << p_array[i].days << endl;
  }

  //delete the array
  delete [] p_array;


  return 0;
}

Friend Resize(Friend* p_array, int* size_of_array)
{
  *size_of_array *= 2;
  Friend *p_new_array = new Friend [*size_of_array];

  for(int i = 0; i < *size_of_array; i++)
  {
    p_new_array[i] = p_array[i];
  }

  delete [] p_array;

  p_array = p_new_array;
}

最佳答案

p_array = p_new_array;

这会将本地 Friend* 参数分配给 p_new_array

为此

p_array[number_of_friends] = f; 

是对无效对象的访问。

Resize 声明为

Friend Resize(Friend** p_array, int* size_of_array)

Friend Resize(Friend*& p_array, int* size_of_array)

解决这个问题。

关于c++ - 数组和指针有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15798066/

相关文章:

c++ - 我可以使用 popt 库一次读取两个选项值吗?

c# - 当与 int 数组和 for 循环一起使用时,使数组中的字符串复数

c - C 中具有返回类型数组的函数

javascript - Jquery 菜单数组在错误的位置打开 ul

c: strtod:双指针与对单指针的引用

c++ - 如何使 wxFrame 表现得像模态 wxDialog 对象

c++ - 如何检索文件数字签名信息?

c++ - 是否可以创建 3d 数组的指针数组?

c++ - 内存管理困惑C++

c++ - 如何通过在 C++ 中的 [] 中传递变量来定义数组的大小?