我的程序是要生成一个动态2D数组,然后进行排序然后转置该数组(错列和行)。我的问题是,当我为行和列输入某个值(7)时,变量索引周围的堆栈进一步损坏了我的代码开始生成自从我认为以来一直没有的数字,因为它超出了范围,请帮助我是c ++的新手。
//
// C++ program template
//
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
void init_array(int ** array_in, int rows, int cols, int list[]);
void print_array(int ** array_in, int rows, int cols);
void selection_sort(int array_in[], int elements);
int ** transpose(int ** array_in, int ** array_out, int rows, int cols);
const unsigned int SIZE = 4000;
int count1 = 0;
int main(void)
{
int rows = 0, cols = 0, j = 0, k = 0;
int**numbers = nullptr;
int**arraytranspose = nullptr;
cout << "Enter rows and columns" << endl;
cin >> rows >> cols;
int length = rows * cols;
int list[4000] = { 0 };
numbers = new int*[rows];
arraytranspose = new int*[rows];
for (k = 0; k < cols; k++)
{
numbers[k] = new int[cols];
arraytranspose[k] = new int[cols];
}
// initialize the array with unique values
init_array(numbers, rows, cols, list);
print_array(numbers, rows, cols);
selection_sort(list, count1);
int count3 = 0;
for (int count2 = 0; count2 < 3999; count2++) {
for (int i = 0; i < rows; i++)
{
for (int c = 0; c < cols; c++)
{
if (list[count2] != 0)
{
numbers[i][c] = list[count2];
}
count2++;
}
}
}
print_array(numbers, rows, cols);
cout << endl << endl;
print_array(transpose(numbers,arraytranspose,rows,cols), rows, cols);
system("pause");
return 0;
}
void selection_sort(int array_in[], int elements)
{
int index = 0, smallest = 0, hold = 0, count = 0, location = 0;
for (index = 0; index < SIZE - 1; index++) // Loop to control number of passes
{
smallest = index;
// Find the index of the smallest element
for (location = index + 1; location < SIZE; location++)
{
if (array_in[location] < array_in[smallest])
{
smallest = location;
} // End If
} // End Inner for loop
hold = array_in[smallest];
array_in[smallest] = array_in[index];
array_in[index] = hold;
count++; // Count number of swaps
}
cout << "There were " << count << " element exchanges during the sort. " << endl << endl;
return;
}
void init_array(int ** array_in, int rows, int cols, int list[])
{
int j = 0, k = 0, value = 0;
int indices[4000] = { 0 };
count1 = 0;
while (j < rows)
{
k = 0;
while (k < cols)
{
value = rand() & 4000;
if (indices[value] != 1)
{
array_in[j][k] = value;
indices[value] = 1;
list[count1] = array_in[j][k];
k++;
count1++;
}
}// end while
j++;
}
return;
}
void print_array(int ** array_in, int rows, int cols)
{
int j = 0, k = 0;
for (j = 0; j < rows; j++) {
for (k = 0; k < cols; k++) {
cout << setw(5) << array_in[j][k];
}
cout << endl;
}
return;
}
int** transpose(int ** array_in, int ** array_out,int rows, int cols)
{
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
array_out[r][c] = array_in[c][r];
}
}
return array_out;
}
我的程序是要生成一个动态2D数组,然后进行排序然后转置该数组(错乱列和行)。我的问题是,当我为行和列输入某个值(7)时,在堆栈周围添加一个堆栈...
numbers = new int*[rows]; arraytranspose = new int*[rows];
这将为一对数组,即
rows
值的数组分配内存。