为什么这会产生分段错误? [英] Why does this generate a segmentation fault?

查看:13
本文介绍了为什么这会产生分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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

<小时><块引用>

arrarr+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'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]

这篇关于为什么这会产生分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆