1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#include <iostream>
#include <cstdlib>
using std::cin;
using std::cout;
// Create memory space for a (rows x cols) c-style array
int** createArray(int rows, int cols)
{
int** array = (int**) malloc( rows*sizeof(int*) );
for(int i = 0; i < rows; i++)
*(array+i) = (int*) malloc( cols*sizeof(int) );
return array;
}
// uses realloc() to dynamically resize the array. Returns
// a pointer to the newly created array
int** resizeArray(int rows, int cols, int** array)
{
int** newarray = (int**) realloc( array, rows*sizeof(int*) );
for(int i = 0; i < rows; i++)
*(newarray+i) = (int*) realloc( *(newarray+i), cols*sizeof(int) );
return newarray;
}
// Free memory
void destroyArray(int rows, int cols, int** array)
{
for(int i = 0; i < rows; i++)
free( *(array + i) );
free(array);
}
// Fill array with random ints
void stuffArray(int rows, int cols, int** array) {
for(int i = 0; i < rows; i++)
for(int j = 0; j < cols; j++)
array[i][j] = rand() % 90 + 10;
}
// Show it
void printArray(int rows, int cols, int** array) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++)
cout << array[i][j] << " ";
cout << "\n";
}
cout << "\n\n";
}
int main()
{
int rows, cols;
cout << "What are the dimensions of your array : ";
cin >> rows >> cols;
int** myArray = createArray(rows, cols);
stuffArray(rows, cols, myArray);
printArray(rows, cols, myArray);
cout << "Enter new dimensions for your array : ";
cin >> rows >> cols;
myArray = resizeArray(rows, cols, myArray);
stuffArray(rows, cols, myArray);
printArray(rows, cols, myArray);
destroyArray(rows, cols, myArray);
return 0;
}
| |