Here is the thing. I can completely understand a concept of a multidimensional array (let's consider 2D for a while) made by pointer to array to pointers and so on...
We do something like this:
// we can use dynamically defined size n and m
int n = 3, m = 5 ;
int **T = new int *[n];
for (int i = 0 ; i < n ; ++i)
T[i] = new int[m];
What we got is: (Check if I'm right here)
- 3 blocks of memory of 5 ints, placed somewhere in memory
- One additional block of memory of same size as number of the blocks of ints (number of rows). This block is an array of pointers (usually 4 bytes for pointer like int) to those int rows.
- What we are interested in most - that is T which is of type (**T) - a pointer to pointer. Which is exactly a pointer to an array of pointer, because in C++ an array is in fact a pointer pointing to a block of memory so t[] or t[0] means *t, and t[x] means *(t+x).
Now the problem is when we do sth like this:
int n = 3, m = 5 ;
int T[n][m] ;
What we've got is not what w could have doing the thing I showed before. We get sth strange. What is T? When printfing T, we get the same value as T[0]. It looks like we reserved a block of ints sized n*m without additional array of pointers to rows.
My question is: does the compiler remembers the dimension of the array and number of rows and columns? And when asking for T[i][j] it actually asks for *(T+i*n+j) so this n is stored somewhere? The problem is when we are trying to pass this thing (T) to a function. I dont know why but if n and m were constants its possible to pass T as a pointer to this array to function like in this program:
#include <stdio.h>
const int n = 3, m = 4 ; // this is constant!
void add_5(int K[][m])
{
for (int i = 0 ; i < n ; ++i)
for (int j = 0 ; j < m ; j++)
K[i][j] += 5 ;
}
int main()
{
// n x m array the most straight forward method
int T[n][m] ;
for (int i = 0 ; i < n ; ++i)
for (int j = 0 ; j < m ; ++j)
T[i][j] = i*m + j ;
for (int i = 0 ; i < n ; ++i)
{
for (int j = 0 ; j < m ; j++)
printf("%d ",T[i][j]) ;
printf("\n") ;
}
printf("\n") ;
// adding 5 to all cells
add_5(T) ;
printf("it worked!!\n") ;
for (int i = 0 ; i < n ; ++i)
{
for (int j = 0 ; j < m ; j++)
printf("%d ",T[i][j]) ;
printf("\n") ;
}
int ss ;
scanf("%d",&ss) ;
}
But if n and m aren't constant we cant. So what I need is to pass dynamically created multidimensional array's pointer to a function without manually allocating memory for that. How to do this?