How to pass a 2d array through pointer in c
c, c++, pointers
Solution
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;
}
}
}
Problem
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?