C/C++ Pointer-Arithmetics
I recently found this when looking up how C/C++ organizes memory when allocating arrays, specifically multi-dimensional arrays.
You can access the array
#define X 5
#define Y 10
int data[X][Y];
either using
data[x][y]
or
*(*(data + x) + y)
won’t this raise a compiler warning? I think I remember something about this…
@stefan
warning just if it’s an array of char (string) in C…so just forget
Unfortunately this isn’t correct hundred percently.
If you program C and define an N-dimensional !static! array, an one dimensional array will be used instead.
What I’d say is that if you want to use an N-dimensional access to an array of values, you have to allocate the data in this way:
// a will be 2-dimensional 20x10
double** a=(double**)malloc(20*sizeof(double*));
for (i=0;i<20;i++)
a[i]=(double*)malloc(10*sizeof(double));
Then you can access a in the 2-dim way a[i][j] instead of computing the index of your own a[i*10+j]. This on the other hand won’t work any more.
If you’d define the array statically without a malloc, you can use both
a[i][j] as well as a[i*10+j], since it’s an one dimensional field internaly
@robert
right he is, i think
@Willi
him or me?
Right YOU are – robert alias “java the hood”
I think both infos are disjunct. Robert’s view is just a third way to do it.