How to pass by reference multidimensional array with unknown size in C or C++?
For example, in main function I have:
int main(){
int
This is a sort of comment to the good answer of @John Bode
This will not work (or at least, not be guaranteed to work) for dynamically allocated arrays of the form:
But this variant will:
T **ap = malloc( M * sizeof *ap );
if (ap) return NULL; ---> some error atention
if (ap)
{
ap[0] = malloc( M * N * sizeof *ap[i] );
if (ap[0]) { free(ap); return NULL;} ---> some error atention
size_t i;
for (i = 1; i < M; i++)
{
ap[i] = ap[0] + i * N;
}
}
After use :
free(ap[0]);
free(ap);
for T
being int
you call foo
exactly als for the array int ap[M][N];
foo( &ap[0][0], M, N);
since you guaranteed that all the rows are allocated contiguously to each other. This allocation is a litter more efficient.