Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

pointers

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?

like image 498
Sayed Hussain Mehdi Avatar asked Dec 23 '12 15:12

Sayed Hussain Mehdi


2 Answers

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.

like image 120
Joseph Mansfield Avatar answered Oct 08 '22 04:10

Joseph Mansfield


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;
        }
    }
}
like image 25
Ramy Al Zuhouri Avatar answered Oct 08 '22 03:10

Ramy Al Zuhouri