0

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

“编写一个程序,让用户跟踪他们最后一次与每个朋友交谈的时间。用户应该能够添加新朋友(尽可能多!)并存储他们最后一次与每个朋友交谈的天数朋友。让用户更新这个值(但不要让他们输入像负值一样的虚假数字)。可以显示按朋友姓名排序的列表,按他们与每个朋友交谈的最近时间。 "

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

它在我输入 5 个朋友后崩溃,所以我猜测它是在数组上写入的,但 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;
}
4

3 回答 3

2
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)

来解决这个问题。

于 2013-04-03T21:06:38.650 回答
0

The problem is that although your resize code is kind of OK, it only changes the pointer inside the Resize function. The pointer in main never gets changed at all. The other error is that you double the size_of_array variable before you copy the array, so you end up copying elements from the old array that don't exist.

Change your function like this

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

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

  delete [] p_array;

  *size_of_array *= 2;
  return p_new_array;
}

And then in main use it like this

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

This way the Resize function returns the new array, and you assign it to the p_array variable in main.,

于 2013-04-03T21:22:41.783 回答
0

崩溃是由于调整大小功能造成的。以下行导致崩溃:

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

您将 size_of_array 的大小增加了一倍,但 p_array 只有 5 个元素。所以这意味着你在这里越界了。

于 2013-04-03T21:10:20.710 回答