为什么这会产生分段错误? [英] Why does this generate a segmentation fault?
问题描述
#include<stdio.h>无效富(int **arr){arr[1][1]++;}主要的() {int arr[20][20];printf("%d
",arr[1][1]);foo((int**)arr);printf("%d
",arr[1][1]);}
<小时>假设您声明:int arr[ 10 ][ 20 ] ;
arr是什么类型的?
您可能认为它是int **
,但这是不正确的.当它衰减时它实际上是
int (*)[20]
类型(就像你将它传递给函数时一样);
数组衰减只应用一次.
现在考虑以下,
#include<stdio.h>#include<stdlib.h>无效 foo(int arr[][20]) {arr[1][1]++;}主要的() {int (*arr)[20];arr = malloc(sizeof(int (*)[]) * 2);//2 行 &malloc 将执行隐式强制转换.printf("%d
",arr[1][1]);富(arr);printf("%d
",arr[1][1]);}
输出:
<块引用>$ gcc fdsf.c &&./a.out
0
1
<小时><块引用>
arr 和 arr+1 指向 20 个整数的数组.
arr + 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
",arr[1][1]);
foo((int**)arr);
printf("%d
",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
",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]
这篇关于为什么这会产生分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!