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?

3
  • 2
    Use proper types, void func(int (*ptr)[2]), or pass an array of pointers. Commented Dec 23, 2012 at 15:10
  • How do I use arrays in C++? Commented Dec 23, 2012 at 15:13
  • Arrays are not pointers. Pointers are not arrays. What you did wrong is not having repeated this to yourself until you stopped doubting it. Commented Dec 23, 2012 at 15:16

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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;
        }
    }
}

2 Comments

Thanks. You made my day. But how to set the i and j if I want to store different things in an array ??
I haven't understood what you mean.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.