dereferencing a 2D dynamic array.

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)
Last edited on
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?
yeah, it is possible, but complicated. Use two index, that's what we usually do at university.

About doing it with one
for example, think on this array

1
2
3
a , b , c , d
e , f , g , h
i , j , k , l

0 is a, ... 3 is d . 4 is e, but in order to access this array, we need to transform ONE coordinate in two coordinates

Here's what i'd do

(x is the width, y is the height)(in this case x = 4, y = 3)
1
2
3
for (unsigned i = 0; i< x*y ; i++) {
    matrix[ i MOD x ][i DIV x] = something; 
}


But as I before said, that's kinda complicated, so better use two indexes. After all you're gonna do the same computational work the two ways.
Last edited on
hey Revor thanks for clearing my doubts. I have implemented as you said using two indexes. It is effectively easier that way.
Thanks!. Please mark the topic as solved. That will help other users who share the same problem.
Topic archived. No new replies allowed.