C语言 二维数组指针



谁能解释一下?

#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("%dt",*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 Functionn");
 FunPrinter(&x[0][0]);
 printf("nOut Functionn");
 for(i = 0; i < 4; i++, printf("n"))
  for(j = 0; j < 5; j++)
   printf("%dt",**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 个有效块可以迭代(不是 20 个)。

在这里,x*x(使用 %p 打印指针,而不是强制转换)是相同的值,因为它们都指向数组的开头(相同的地址),但指针算法不同(元素的大小不同)。您可以通过可能需要将其转换为int * x进行迭代。

此外,您在FunPrinter中使用的方法 - 将 2D 数组降级为 1D 数组并不能保证有效,它确实涉及未定义的行为(尽管大多数合理的编译器都可以很好地编译它)。