Dear Forum,
I have got stuck on this for some time. I am creating a 2D dynamic float array and want to store some values there. I am having problems to access the positions i-line, j-column using pointers.
//declaration of dynamic array
w= new float*[N_row];
for (int p=0; p<N_row; p++)
w[p]= new float[N_col];
//I stored some values using w[i][j] in a loop. It goes fine.
for (int i=0; i<N_row; i++)
for (int j=0; j<N_col; j++)
w[i][j]=i*j+1;
endl(cout);
But when I want to access my array using pointer I can only access the column position of the first row. For example, if N_row=N_col=5...
The expression:
*(*w+4)=19;
stores the int 19 in the (first row;fifth column)
But the expression:
*w+10=19;
does not store the int 19 in the (third row; first column) as I would expect. It stores my values in a rather random and changing position on the array. I must be missing something. The reason i want to use pointer to dereference the array is because I want to use only one increment variable in a for loop. Sort of w++
Thanks for help,
JP
I think *w+10=19; is not working as you think it should.
When you do *w +10 = something, you're assigning something to the DIRECTION contained in *w +10 (remember w is a pointer to pointers,consequently *w is a pointer). If you want to modify the content in there, try this instead
*( *(w+coordinate1) + coordinate2) = something
(BTW, Why don't you access the position as w[i][j] = something ? That's a lot easier)
Hey JRevor,
thanks for your answer. I tried this way and effectively it works. The memory positions in two arrays are different. I wanted to use a pointer hopping that with only one variable i could refer to any position in the matrix. With w[i][j] i need two variables to move across the matrix positions. But then with pointers i still need two dereferencing coordinates.
It it possible to move with only one increment variable?