-9

So I have the following code so far:

#include <stdio.h>

int foo (int *pointer, int row, int col); 

int main() {
  int array[3][3] ={ {1,2,3},{4,5,6},{7,8,9}};

  int *pointer= array[0];

  int row = 2; 
  int col = 2; 

  int answer = foo (pointer, row, col); 

  printf("%d", answer); //prints 5 (which is wrong)
  printf("%d", array[2][2]); //prints 9
}

int foo (int *pointer, int row, int col){ //I don't want to use any square brackets here, unless I really have to. 
  int value; 
  value = *((int *)(pointer+row)+col); 

return value; 
}

So my main issue is with passing a 2D pointer, please explain in detail as I am still new at coding. I don't want to really change what I am passing (as in I want to use the pointer in foo(pointer, row, col) and not foo (array, row, col).

  • @Dayalrai What about it, huh? All I can say about it is that it's terribly wrong and strengthens the "arrays are pointers" mischief. –  May 14 '13 at 09:13
  • @Dayalrai You're wrong in that you use multidimensional arrays and double pointers interchangeably, which they aren't. –  May 14 '13 at 09:16
  • 1
    why you have removed the question. Put this phrase as commanet and do not remove your original question – MOHAMED May 14 '13 at 09:21
  • @MOHAMED Rolled back. –  May 14 '13 at 09:23
  • @ MOHAMED. Sorry my bad. I thought that would be the best way for it to be seen. So anyway can someone point me to a good resource explaining the distinction between arrays and pointers :) – user2380876 May 14 '13 at 09:26
  • [C strings pointer vs. arrays](http://stackoverflow.com/questions/3207286/c-strings-pointer-vs-arrays) – MOHAMED May 14 '13 at 09:32

2 Answers2

3

passing a 2D pointer

From how you (ab)used the terminology, it's quite clear that you're under the wrong impression that pointers and arrays are the same. They aren't.

If you want to access a multidimensional array using pointers, you must specify all its dimensions (except the first, innermost one) and use pointer arithmetic correctly, possibly using pointers-to-array, since multidimensional arrays are contiguous in memory:

const size_t h = 2;
const size_t w = 3;
int arr[h][w] = {
    { 1, 2, 3 },
    { 4, 5, 6 }
};

int *p = &arr[1][2];
int *q = arr[1];
int (*t)[3] = &arr[1];
printf("arr[1][2] == %d == %d == %d\n", *p, q[2], (*t)[2]);

return 0;
1
int *pointer= array[0];

Instead of use this

int *pointer= &array[0];

Or

int *pointer= array;
Rohan
  • 52,392
  • 12
  • 90
  • 87