Segmentation Fault in C – Why This Code Generates an Error

arraysc++segmentation-fault

#include<stdio.h>
void foo(int **arr) {
    arr[1][1]++;
}

main() {
    int arr[20][20];
    printf("%d\n",arr[1][1]);
    foo((int**)arr);
    printf("%d\n",arr[1][1]);
}

Best Answer

Suppose you declare: int arr[ 10 ][ 20 ] ;
What type is arr?
You may think that it's int **, but that's incorrect.

Its actually of type int (*)[20] when it decays (like when you pass it to a function);
Array decaying applies only once.

Details here


Now consider the following,

#include<stdio.h>
#include<stdlib.h>
void foo(int arr[][20]) {
  arr[1][1]++;
}
main() {
  int (*arr)[20];
  arr = malloc(sizeof(int (*)[]) * 2); //2 rows & malloc will do implicit cast.

  printf("%d\n",arr[1][1]);
  foo(arr);
  printf("%d\n",arr[1][1]);
}

Output :

$ gcc fdsf.c && ./a.out
0
1


arr and arr+1 are pointing to array of 20 integers.

arr + 0 --> int       int       int    ...    int (20 ints, contiguous)
             [0][0]   [0][1]
arr + 1 --> int       int       int    ...    int (20 ints, contiguous)
             [1][0]   [1][1]

Related Question