As an example:
int *a == int a[]
int **b == int b[][]
int ***c == int c[][][]
let me clarify, I am simply saying these are equivalent in terms that the variable name represents the same thing a pointer to an int, a pointer to a pointer to an int, etc...
when you do
int a[4][4] the variable is actually
a pointer to a pointer to an int not
a pointer to an int . By calling it 1D you are removing a level of indirection, hence you are calling it
a pointer to an int .
The fact that the compiler may allocate a linear portion of memory and possibly collapse it to a 1D array does not remove the fact it requires 2 levels of indirection to access the data.
My point is the original poster is trying to learn about pointers. What everyone is telling him about is a
special case where the memory is allocated by the compiler at compile time. The fact is it is two dimensional due to the fact it requires to levels of indirection.
Take the sample code which prints the addresses of the different levels of indexing. Notice when you allocate it on you own it requires two levels of indirections, which shows that the preallocated compiler variable is a special case. Also notice the index notation used on v2 even though it was declared unsigned int **v2. This demonstrates what I mean by the fact the above expressions are equivalent.
Code: Select all
#include <stdio.h>
#include <stdlib.h>
void main()
{
unsigned int x, y;
unsigned int v1[4][4];
unsigned int **v2;
// lets initialize v1
for( x = 0; x < 4; x++ )
for( y = 0; y < 4; y++ )
v1[x][y] = (x* 4) + y;
// lets allocate memory for v2
v2 = (unsigned int**) malloc( sizeof(int*) * 4 );
for( x = 0; x < 4; x++ )
v2[x] = (unsigned int*) malloc( sizeof(int) * 4 );
// lets initialize v2
for( x = 0; x < 4; x++ )
for( y = 0; y < 4; y++ )
v2[x][y] = (x* 4) + y;
// Print addresses of the Compiler allocated memory vs Dynamic Allocation
printf( "compiler dynamic\r\n" );
printf( "========================================\r\n" );
for( x = 0; x < 4; x++ )
{
printf( "v1[%u]: %#08X \t", x, &v1[x] );
printf( "v2[%u]: %#08X\r\n", x, &v2[x] );
for( y = 0; y < 4; y++ )
{
printf( "v1[%u][%u]: %#08X\t", x, y, &v1[x][y] );
printf( "v2[%u][%u]: %#08X\r\n", x, y, &v2[x][y] );
}
}
// free memory
for( x = 0; x < 4; x++ )
free( v2[x] );
free(v2);
}