我的C++程序有问题.涉及动态调整整数数组的大小

Having trouble with my C++ program. Involes resizing an integer array dynamically

本文关键字:数组 整数 调整 动态 程序 C++ 有问题 我的      更新时间:2023-10-16

这是我目前所拥有的:http://cpp.sh/54vn3

#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <cstdlib>
using namespace std;
int *reSIZE(int *&original, int &SIZE, const int &maxSIZE); //function prototype resize
void sortFUNC(int *&original, int &SIZE, const int &maxSIZE); //function prototype sortFUNC
int main()
{
int SIZE = 4; //size of current array
int maxSIZE = 10; //size of final array
int *original = new int[SIZE] {5, 7, 3, 1}; //old(current) array
cout << "Elements in array: "; //test output
reSIZE(original, SIZE, maxSIZE); //call function resize
cout << endl << endl; //blank line
cout << "Elements in array in increasing order: "; //test output
sortFUNC(original, SIZE, maxSIZE); //call function sortFUNC
cout << endl << endl;
return 0;
}
int *reSIZE(int *&original, int &SIZE, const int &maxSIZE)//function definition
{
int *temporiginal = new int[SIZE + 3]; //(final)new array
for (int i = 0; i < SIZE; i++) //copy old array to new array
{
temporiginal[i] = original[i];
cout << original[i] << setw(3);
}
delete[] original; //delete old array
original = temporiginal; //point old array to new array
return temporiginal;
}
void sortFUNC(int *&original, int &SIZE, const int &maxSIZE)
{
for (int i = 0; i < SIZE; i++)
{
int smallest = original[i];
int smallestINDEX = i;
for (int m = i; m < SIZE; m++)
{
if (original[m] < smallest)
{
smallest = original[m];
smallestINDEX = m;
}
}
swap(original[i], original[smallestINDEX]);
}
int *temporiginal = new int[SIZE + 3];
for (int i = 0; i < SIZE; i++)
{
temporiginal[i] = original[i];
cout << original[i] << setw(3);
}
delete[] original;
original = temporiginal;
}

我想在 main 的数组末尾添加一些元素,但是当我这样做时,程序在我运行时崩溃。我创建的 resize 函数应该扩展 main 中的函数以容纳 10 个元素。主楼原本有4个。新数组应该将其更改为 10。如何在 main 中向数组再添加三个整数而不会崩溃?我的调整大小功能有误吗?还是我的主要问题?现在显示的程序按原样工作。但是当我在 main 的数组中添加另一个整数时,它会崩溃。就像,如果我在 2 之后添加一个 1。

谢谢。

编辑:通过在调整大小功能中添加元素,我能够在 main 的数组末尾添加元素。

cpp.sh/35mww

如前所述,maxSIZE未被使用。还有更多无用的东西。我必须清理一下,但我想出了我想弄清楚的是什么。我还不知道如何使用结构。我知道有很多不同的方法来编写程序。我只是一个初学者。

谢谢大家。

每次调用函数时,您都需要修改大小的值 rezise 其他明智,即使您调用函数 resize 3 次,您的数组大小总是会有 SIZE+3。调用调整大小后尝试

original[4] = 0;
original[5] = 0;
original[6] = 0;

然后尝试这样做。

original[7] = 0;

你应该能够看到你的错误