Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

c - Why does this generate a segmentation fault?

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

main() {
    int arr[20][20];
    printf("%d
",arr[1][1]);
    foo((int**)arr);
    printf("%d
",arr[1][1]);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
",arr[1][1]);
  foo(arr);
  printf("%d
",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]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...