【问题标题】:Two dimensional array pointer issue二维数组指针问题
【发布时间】:2014-01-20 16:43:17
【问题描述】:

我正在尝试理解 C 中二维数组的指针算法。

void pmanipulation(int arr[][5],int rows)
{
printf("arr=%d  arr+1=%d  *(arr)=%d *(arr+1)=%d\n",arr,arr+1,*(arr),*(arr+1));
}

在上面的小代码sn-p中,我观察到arr+i和*(arr+i)打印出来的值显然没有什么不同。为什么会这样?我知道在 C 中 arr+i 将给出二维矩阵第 i 行的基地址,但 *(arr+i) 不应该在该地址打印元素吗?

谢谢

【问题讨论】:

  • *(arr+i) 是一个长度为 5 的数组。你能用printf() 打印数组吗?是的,但只有char 数组(= C 字符串)。你有一个int 数组。还有*(arr+i)给你第i行第一个元素的地址,而arr+i给你整个第一行的地址,这与*(arr+i)相同,但有细微的差别,即*((arr+i)[n]) 正在逐步进入n*5 的元素,而(*(arr+i))[n] 仅在n 的步骤中。
  • @mb84- 非常感谢您的解释。

标签: arrays pointers


【解决方案1】:

让我们考虑这个简单的程序:

#include <stdio.h>

void main(){
    int i,j;
    int a[3][5];
    for(i=0;i<3;i++){
        for(j=0;j<5;j++){
            a[i][j]=i*10+j;
        }
    }
    printf("a=%d a+1=%d *(a)=%d *(a+1)=%d\n", a, a+1, *(a), *(a+1));
}

当你用 gcc 编译时,你会得到:

test.c: In function 'main':
test.c:11:2: warning: format '%d' expects argument of type 'int', but argument 2 has type 'int (*)[5]' [-Wformat]
test.c:11:2: warning: format '%d' expects argument of type 'int', but argument 3 has type 'int (*)[5]' [-Wformat]
test.c:11:2: warning: format '%d' expects argument of type 'int', but argument 4 has type 'int (*)' [-Wformat]
test.c:11:2: warning: format '%d' expects argument of type 'int', but argument 5 has type 'int (*)' [-Wformat]

您会注意到*(a+1) 仍然是一个指针。由于这是一个二维数组,因此您需要进行双重取消引用才能获得值**(a+1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 2021-12-17
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多