Originally Posted by
cooper1200
maybe im being thick but any 2d array needs two co-ordinates to access a single cell for example in a 10 x 10 array i would have to write [3][5] to access a specific location
Yep... but bidimensional arrays are shortcuts to unidimensional ones. a[3][5], in an array a defined as a[10][10] is the same as *(a + 10*3 + 5):
Code:
#include <stdio.h>
// Show the array using bidimensional notation...
int show_array( int a[][4] )
{
int i, j;
for (i = 0; i < 3; i++)
{
fputs( "{ ", stdout );
for (j = 0; j < 3; j++)
printf( "%d, ", a[i][j] );
printf( "%d }\n", a[i][3] );
}
putchar('\n');
}
int main( void )
{
static int a[3][4] = { {0} }; // filled with zeros...
int *p;
int i, j;
// Fill with i*j using bidimensional notation.
for ( i = 0; i < 3; i++)
for (j = 0; j < 4; j++ )
a[i][j] = i*j;
show_array( a );
// Fill with NEGATIVE i*j using a pointer and an offset.
p = (int *)a;
for ( i = 0; i < 3; i++)
for ( j = 0; j < 4; j++)
*(p + 4*i + j) = -i*j; // Notice: pointer + ("columns"*i + j).
show_array( a );
}
With 'incomplete' arrays you MUST declare them with only the highest dimension blank because the compiler need the lower dimensions to calculate the correct pointer (see the int a[][4] in show_array argument).