Return a 2d array from a function
This code returns a 2d array.
#include <cstdio>
// Returns a pointer to a newly created 2d array the array2D has size [height x width]
int** create2DArray(unsigned height, unsigned width)
{
int** array2D = 0;
array2D = new int*[height];
for (int h = 0; h < height; h++)
{
array2D[h] = new int[width];
for (int w = 0; w < width; w++)
{
// fill in some initial values
// (filling in zeros would be more logic, but this is just for the example)
array2D[h][w] = w + width * h;
}
}
return array2D;
}
int main()
{
printf("Creating a 2D array2D\n");
printf("\n");
int height = 15;
int width = 10;
int** my2DArray = create2DArray(height, width);
printf("Array sized [%i,%i] created.\n\n", height, width);
// print contents of the array2D
printf("Array contents: \n");
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width; w++)
{
printf("%i,", my2DArray[h][w]);
}
printf("\n");
}
// important: clean up memory
printf("\n");
printf("Cleaning up memory...\n");
for (int h = 0; h < height; h++) // loop variable wasn't declared
{
delete [] my2DArray[h];
}
delete [] my2DArray;
my2DArray = 0;
printf("Ready.\n");
return 0;
}
A better alternative to using pointers to pointers is to use std::vector
. That takes care of the details of memory allocation and deallocation.
std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width)
{
return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));
}
That code isn't going to work, and it's not going to help you learn proper C++ if we fix it. It's better if you do something different. Raw arrays (especially multi-dimensional arrays) are difficult to pass correctly to and from functions. I think you'll be much better off starting with an object that represents an array but can be safely copied. Look up the documentation for std::vector
.
In your code, you could use vector<vector<int> >
or you could simulate a 2-D array with a 36-element vector<int>
.