Reputation: 31
I'm trying to understand pointer arithmetic in 2D vector.
I thought that if I have 2D vector at the size: M[3][3]
and *ptr=&M[0][0]
than ptr[4]
is equal to M[1][2]
, but it seems to be wrong.
Can you please help me out with this?
Upvotes: 1
Views: 499
Reputation: 308530
2D arrays are arranged in Row-major order, so the 3 columns of row 0 come first, followed by the 3 columns of row 1, etc. Your concept is correct, but your counting is off: it's M[1][1].
Note that you might run into problems due to pointer aliasing depending on your code and how agressively your compiler tries to optimize.
Upvotes: 2
Reputation: 96167
M[3][3] is laid out in memory as [0,0] [0,1] [0,2] [1,0] [1,1] [1,2] [2,0] [2,1] [2,2]
so ptr+4 would be the fourth element of the array [1,1] but since you defined it as a 2d array you can't use a 1d index as shorthand.
Upvotes: 1