# Pointer Arithmetic

• 11-13-2008
taurus
Pointer Arithmetic
Hi I have a question,
Say i got the 2D array below:
Code:

```1 2 3 4 5 6 7 8 9```
How can i access row 2, column 3 using pointer arithmetic (should be 6)?
• 11-13-2008
matsp
ptr + 5?

--
Mats
• 11-13-2008
taurus
But like this:
Code:

```#include <stdio.h> int read_element ( int *, int, int, int, int); int main() {         int array[3][3] = {{1,2,3},{4,5,6},{7,8,9}};         int element = read_element(&array[0][0],3,3,2,1);         printf("&#37;d\n",element); } int read_element(int *ptr, int row, int col, int x, int y) {         return *(ptr+col*y+x); }```
I cant get my function to work?
• 11-13-2008
matsp
Looks right to me. When I try it, I get 6, and if I print array[1][2], I also get 6, so what's wrong with that?

--
Mats
• 11-14-2008
P4R4N01D
What are y and x? You already pass the row and col, so why are they needed? Also &array[0][0] can be written as array as the address of an array is naturally the address of its first element. This might come in more helpful with more diamensions.
Also why is row passed when it is not used?
• 11-14-2008
matsp
Quote:

Originally Posted by P4R4N01D
What are y and x? You already pass the row and col, so why are they needed? Also &array[0][0] can be written as array as the address of an array is naturally the address of its first element. This might come in more helpful with more diamensions.

caveat emptor: I didn't write this code.

x & y are the "coordinates" in the array that we want to get to. row and col probably should be called "rows" and "cols" to be more descriptive, as it is the number of rows and columns respectively.

&array[0][0] could be written as array[0], but I actually prefer the way taurus did it. If you want to just pass the array, you'd need to cast it, as the type of array is int (*array)[3], not int * - so the compiler will moan about type conversion.

Quote:

Also why is row passed when it is not used?
That is correct. However, we could add a bit of error checking if we have the rows as well as columns, to validate that x & y are within bounds.

--
Mats