Pointer to a 2D Array as a Function Parameter

Hello,

I am having a hard time with a problem. Basically, I am to create a pointer to a 2-dimensional array of ints, say 3x3, and then this pointer will be used as a parameter when a function is called. I would post code but it is so messed up I don't think it would be useful. I've been reading widely conflicting things on the internet about how to code this. I am having trouble with making the prototype, definition, and function call work together.

Any help would be very appreciated! I can supply more info if needed. Thank you!

P.S. Some people say this is dumb because an array is technically already a pointer, but the assignment calls for a pointer to an array so that's what I need to do.
The easiest way it to create a pointer of the same data type and then to pass the starting address of the array into it.

1
2
int array[3][3];
int *ptr = array;


The last line passes the address of the starting position of the array into ptr. Now you need to access the array using the pointer.

1
2
3
4
5
for(size_t i = 0; i < 3; i++)
{
    for(size_t j = 0; j < 3; j++)
         *(ptr + i +j) = i + j;
}


This way you can access or modify the data in the array by using a pointer. Now as you said the array is also a pointer so you can also use the following code.

1
2
3
4
5
for(size_t i = 0; i < 3; i++)
{
   for(size_t j = 0; j < 3; j++)
      *(array + i +j) = i + j;
}


If you need any further assistance then do contact me.
Thank you so much! I will try this out and see if that helps.
So I am still getting this error: "cannot initialize a variable to type 'int *' with an lvalue of type 'int[3][3]' " referring to the line

int *ptr = array;

Also, when I send the pointer into a function, would it be

myFunction(ptr);

or

myFunction(&ptr);

And what would the function prototype and definition look like? I think that is where these errors are coming from. Thank you again.
@Stalker
No, that doesn't work. You do as if array is a 1d array, but it isn't (even then the calculation would be wrong).

@ajens
You can pass a 2d array like so:
1
2
3
4
5
6
7
8
9
10
void foo(int array[3][3]) // The first dimension is optional, the second is required
{
...
}

int main()
{
  int array[3][3];
  foo(array);
}
Last edited on
coder777, where I'm having trouble is I'm supposed to pass a pointer to the array, not the array itself.
Topic archived. No new replies allowed.