I am currently doing a project where I am going to pass a 2D pointer array to a function. Here is the function implementation:
void
affiche_Tab2D(int *ptr, int n, int m)
{
if (n>0 && m>0 && ptr!=NULL)
{
int (*lignePtr)[m]; // <-- Its my first time to see this declaration
lignePtr = (int (*)[m]) ptr; // <-- and this too....
for (int i = 0 ; i < n ; i++)
{
for (int j = 0 ; j < m ; j++)
{
printf("%5d ",lignePtr[i][j]);
}
printf("\b\n");
}
}
}
Notice that ptr is 2D array but it uses a single pointer. Before, I used to pass 2D array using double pointers. In my main I have set up a 2D array (double pointer) and finding ways how to send it to that function.
Here are the function calls I tried which does not work:
int
main(int argc, char * argv[])
{
int ** numbers_table;
int i, j;
numbers_table = (int **)malloc(10 * sizeof(int *));
for(i = 0; i < 10; i++)
numbers_table[i] = (int *)malloc(10 * sizeof(int));
for(i = 0; i < 10; i++)
for(j = 0; j < 10; j++)
numbers_table[i][j] = i + j;
// Failed function call 1
// affiche_Tab2D(numbers_table, 10, 10);
// Failed function call 2
// affiche_Tab2D(&numbers_table, 10, 10);
for(i = 0; i < 10; i++)
free(numbers_table[i]);
free(numbers_table);
return 0;
}