为什么以下代码会出现分段错误错误
#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));
}
答案 0 :(得分: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.
答案 1 :(得分: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.
}
答案 2 :(得分:1)
这是c
定义中的问题。 int **c;
表明这是指向指针的指针,但a
的定义属于int *[2]
类型。将c
的定义更改为int (*c)[2]
应该可以解决问题。