0

为什么以下代码给出分段错误错误

#include<stdio.h>
int main()
{
    int i;
    int a[2][2]={1,2,3,4};

    int **c;
    c=a;
    for(i=0;i<4;i++)
        printf("%d",*(*(c)+i));
}
4

3 回答 3

7

本次作业:

c=a;

应该给你一个警告。 a衰减为指向其第一个元素的指针,该元素具有int (*)[2]. 将该类型分配给类型变量int **需要显式转换。

重新声明c应该可以解决您的问题:

int (*c)[2];

来自 clang 的示例警告:

example.c:8:6: warning: incompatible pointer types assigning to 'int **' from
      'int [2][2]' [-Wincompatible-pointer-types]
    c=a;
     ^~
1 warning generated.
于 2013-09-18T18:32:30.947 回答
2

阅读以下代码的注释:

#include<stdio.h>

int main()
{
    int i;
    int a[2][2]={{1,2},{3,4}};    // Put each dimension in its braces

  /*int a[2][2]={1,2,3,4}; 
    This declaration of array make the following: 

       a1[ONE]           a2[TWO]           THREE           FOUR 
       a3[Unknown value] a4[Unknown value] 

    i.e. the numbers 3 and 4 are being written beyond of the array...
  */

    int *c1;
    int **c2;                     // `int **` is a pointer to a pointer, so you have to
    c1=&a[0][0];                  // declare a pointer `c1` and then assign to it `c2`.
    c2=&c1;                       // AND use `&` to assing to pointer the address of 
                                  // variable, not its value.
    for(i=0;i<4;i++)
        printf("%d",*(*(c2)+i));  // here is `double dereference` so here must be `c2`
                                  // (ptr-to-ptr-to-int) but not c1 (ptr-to-int).
    return 0;                     // AND make the `main()` to return an `int` or
                                  // make the returning type `void`: `void main(){}`
                                  // to make the `main()` function to return nothing.
}
于 2013-09-18T18:32:10.803 回答
1

这是定义中的一个问题cint **c;暗示 this 是一个指向指针的指针,但其定义a是 type int *[2]。更改cto的定义int (*c)[2]应该可以解决问题。

于 2013-09-18T18:47:17.157 回答