How to pass a 2d array through pointer in c [duplicate]

Possible Duplicate:
Passing a pointer representing a 2D array to a function in C++

I am trying to pass my 2-dimensional array to a function through pointer and want to modify the values.

#include <stdio.h>

void func(int **ptr);

int main() {
    int array[2][2] = {
        {2, 5}, {3, 6}
    };

    func(array);

    printf("%d", array[0][0]);
    getch();
}

void func(int **ptr) {
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            ptr[i][j] = 8;
        }
    }
}

But the program crashes with this. What did I do wrong?


Solution 1:

Your array is of type int[2][2] ("array of 2 array of 2 int") and its name will decay to a pointer to its first element which would be of type int(*)[2] ("pointer to array of 2 int"). So your func needs to take an argument of this type:

void func(int (*ptr)[2]);
// equivalently:
// void func(int ptr[][2]);

Alternatively, you can take a reference to the array type ("reference to array of 2 array of 2 int"):

void func(int (&ptr)[2][2]);

Make sure you change both the declaration and the definition.

Solution 2:

It crashes because an array isn't a pointer to pointer, it will try reading array values as if they're pointers, but an array contains just the data without any pointer.
An array is all adjacent in memory, just accept a single pointer and do a cast when calling the function:

func((int*)array);

...

void func(int *ptr) {
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            ptr[i+j*2]=8;
        }
    }
}