#include <stdio.h>
void func(int **arr, int s) {
for (int i = 0; i < s; i++) {
for (int j = 0; j < s; j++) {
printf("%d\n", arr[i][j]);
}
}
printf("\n");
}
int main() {
int arr[3][3] = {
{11, 12, 13},
{21, 22, 23},
{31, 32, 33},
};
func((int**)arr, 3);
}
In this code I'm trying to pass a 2D array to another function and have the second function print out all it's values. I've chosen to specify the array as a int **
in the signature of the function (loosely following the second method specified in this example).
When I run this code I expect it to be able to print out all the items, but instead it seg faults and I'm not sure why. I've tried debugging it, but gdb points me to the printf
's array access in the func
function, but I already suspected that's the cause. There is obviously a discrepency between what I think the memory looks like and how i'm trying to access it and how it's actaully being accessed (or what's being accessed).