为什么会产生这种分割故障? [英] Why does this generate a segmentation fault?
问题描述
#包括LT&;&stdio.h中GT;
无效美孚(INT ** ARR){
改编[1] [1] ++;
}主(){
INT ARR [20] [20];
的printf(%d个\\ N,编曲[1] [1]);
美孚((INT **)ARR);
的printf(%d个\\ N,编曲[1] [1]);
}
假设你声明:
INT ARR [10] [20];结果
什么类型的ARR?结果
你可能会认为这是INT **
,但这是不正确。
它实际上类型的
INT(*)[20]当它衰变(当你把它传递给一个函数等)
;结果
阵列衰减仅适用一次。
块引用>现在考虑以下
#包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
无效美孚(INT改编[] [20]){
改编[1] [1] ++;
}
主(){
INT(*改编)[20];
ARR =的malloc(sizeof的(INT(*)[])* 2); // 2行&安培;的malloc会做隐式转换。 的printf(%d个\\ N,编曲[1] [1]);
富(ARR);
的printf(%d个\\ N,编曲[1] [1]);
}输出:
$ GCC fdsf.c&放大器;&安培; ./a.out结果
0结果
1
块引用>
改编和改编+ 1 指向20整数数组。
编曲+ 0 - > int int int ... int (20整数,连续的)结果
             [0] [0]鸟   [0] [1]结果
ARR + 1 - > int int int ... int (20整数,连续的)结果
             [1] [0]鸟   [1] [1]
块引用>#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]); }
解决方案Suppose you declare: int arr[ 10 ][ 20 ] ;
What type is arr?
You may think that it'sint **
, 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.
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]
这篇关于为什么会产生这种分割故障?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!