1. ## 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)? 2. ptr + 5?

--
Mats 3. But like this:
Code:
```#include <stdio.h>
int read_element ( int *, int, int, int, int);
int main()
{
int array = {{1,2,3},{4,5,6},{7,8,9}};
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? 4. Looks right to me. When I try it, I get 6, and if I print array, I also get 6, so what's wrong with that?

--
Mats 5. What are y and x? You already pass the row and col, so why are they needed? Also &array 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? 6. Originally Posted by P4R4N01D What are y and x? You already pass the row and col, so why are they needed? Also &array 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 could be written as array, 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), not int * - so the compiler will moan about type conversion.

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 Popular pages Recent additions 