Hi I have a question,
Say i got the 2D array below:
How can i access row 2, column 3 using pointer arithmetic (should be 6)?Code:1 2 3 4 5 6 7 8 9
Hi I have a question,
Say i got the 2D array below:
How can i access row 2, column 3 using pointer arithmetic (should be 6)?Code:1 2 3 4 5 6 7 8 9
ptr + 5?
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
But like this:
I cant get my function to work?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("%d\n",element); } int read_element(int *ptr, int row, int col, int x, int y) { return *(ptr+col*y+x); }
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
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
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?
long time no C; //seige
You miss 100% of the people you don't C;
Code:if (language != LANG_C && language != LANG_CPP) drown(language);
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.
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.Also why is row passed when it is not used?
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.