我的C++程序有问题.涉及动态调整整数数组的大小
Having trouble with my C++ program. Involes resizing an integer array dynamically
这是我目前所拥有的: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;
你应该能够看到你的错误
相关文章:
- C++使用整数的压缩数组初始化对象
- 在一定长度后从数组中打印时缺少整数
- 是否基于数组B整数打印数组A中的整数
- 检查TCHAR数组输入是否为带符号整数C++
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 从二进制文件中读取整数数组
- 整数区间(或 int 数组)中每个数字的出现次数
- 新的整数数组向右移动?
- C++ 中的二维整数数组,每行中的元素数量不均匀
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 为什么在我的 main 函数中声明整数后我的整数数组中会出现错误?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 在 C++ 中将整数数组转换为位集表示形式的最佳方法?
- C++数组输入不接受一定数量的整数
- 从两个 4x64 位整数数组中获取取模
- 如何计算数组整数的总可能组合
- 2D 字符串数组 C++:整数串联成字符串
- 将数组整数2除以偶数和
- 将2d数组整数数据从c++发送到qml