If a 2d array is created int 2DRepresentation[mapWidth][mapHeight]; inside a function, what is the best way to return this?
how does the function return look?
Would it be preferred to rather create a pointer to a 2d array and pass it into a function, modifying it within the function? If so, how does a pointer to a 2D array look? Like this:
int *2DRepresentation[mapWidth][mapHeight]; ?
How would the function parameter look like which accepts a 2d array pointer?
You will have to return the base address of the array, i.e., a Pointer. However the only solution is that you will have to make the array static otherwise once the function goes out of scope, it will get destroyed. If you don't want to make it static you should use dynamic memory allocation.
Sample pseudo-code:
int **array; // array is a pointer-to-pointer-to-int
array = malloc(mapHeight * sizeof(int *));
if(array == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
for(i = 0; i < mapHeight ; i++)
{
array[i] = malloc(mapWidth * sizeof(int));
if(array[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit or return
}
}
This is how you might pass it into a function named foo say:
foo(int **array, int _mapHeight, int _mapWidth)
{
}
Arrays decay into pointers, hence you need to pass the rows and column values as separate arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With