8

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?

Community
  • 1
  • 1

2 Answers2

9

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.

Joseph Mansfield
  • 100,738
  • 18
  • 225
  • 303
3

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;
        }
    }
}
Ramy Al Zuhouri
  • 20,942
  • 23
  • 94
  • 176