有人能解释一下吗?
#include<stdio.h>
void FunPrinter(int *x)
{
int i, j;
for(i = 0; i < 4; i++, printf("\n"))
for(j = 0; j < 5; j++)
printf("%d\t",*x++);
}
int main()
{
int x[][5] = {
{17, 5, 87, 16, 99},
{65, 74, 58, 36, 6},
{30, 41, 50, 3, 54},
{40, 63, 65, 43, 4}
};
int i, j;
int **xptr = x;
printf("Addr:%ld,Val:%ld,ValR:%ld",(long int)x,(long int)*x,(long int)**x);
printf("\nInto Function\n");
FunPrinter(&x[0][0]);
printf("\nOut Function\n");
for(i = 0; i < 4; i++, printf("\n"))
for(j = 0; j < 5; j++)
printf("%d\t",**xptr++);
return 0;
}
输出:
Addr:140734386077088,Val:140734386077088,ValR:17
Into Function
17 5 87 16 99
65 74 58 36 6
30 41 50 3 54
40 63 65 43 4
Out Function
Segmentation fault (core dumped)
为什么直接寻址不起作用?我正在通过指针访问。我使用了双指针,但它不起作用。 我也尝试过使用单指针作为 xptr。但还是不行。
最佳答案
您遇到了段错误,因为您正在迭代错误的指针(在最外层的维度指针上)。您可以迭代的那个维度上只有 4 个有效 block (不是 20 个)。
这里,x
和*x
(使用%p
打印指针,不是强制转换)是相同的值,因为它们都指向到数组的开头(相同的地址),但指针算法不同(元素的大小不同)。您可以通过 x
进行迭代,可能需要将其转换为 int *
。
此外,您在 FunPrinter
中使用的方法 - 不能保证将 2D 数组降级为 1D 数组,它确实涉及未定义的行为(尽管大多数合理的编译器会很好地编译它).
关于c - 二维数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12578218/