鱼C论坛

 找回密码
 立即注册
查看: 1463|回复: 3

二維數組指針問題

[复制链接]
发表于 2022-4-10 15:53:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
一个二维数组
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};


printf("%d,%d"a+1,*(a+1));
是同樣的

printf("%d,%d"a+1+2,*(a+1)+2);

為什麼不行,而且值也很奇怪
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-4-10 16:33:30 | 显示全部楼层

回帖奖励 +1 鱼币

从编译出现警告其实就比较容易知道了。
你操作类型不同,一个是数组指针,一个是指针。
test.c: In function ‘main’:
test.c:8:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int (*)[4]’ [-Wformat=]
    8 |     printf("%d,%d\n",a+1,*(a+1));
      |             ~^       ~~~
      |              |        |
      |              int      int (*)[4]
test.c:8:17: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘int *’ [-Wformat=]
    8 |     printf("%d,%d\n",a+1,*(a+1));
      |                ~^         ~~~~~
      |                 |           |
      |                 int         int *
      |                %ls
test.c:10:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int (*)[4]’ [-Wformat=]
   10 |     printf("%d,%d",a+1+2,*(a+1)+2);
      |             ~^     ~~~~~
      |              |        |
      |              int      int (*)[4]
test.c:10:17: warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘int *’ [-Wformat=]
   10 |     printf("%d,%d",a+1+2,*(a+1)+2);
      |                ~^        ~~~~~~~~
      |                 |              |
      |                 int            int *
      |                %ls
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-4-10 16:38:39 | 显示全部楼层

回帖奖励 +1 鱼币

#include <stdio.h>

int main()
{
       int a[3][4]={1,2,3,4,
                   5,6,7,8,9,
                   10,11,12};

        int *p = a[0]; // 指针变量
printf("%d\n ",  *(p+1)); // 指针变量

printf("%d\n",  *(*(a+1)+1)); // 二维数组指针索引。 a+1 定们到行, *(a+1) 该行首元素地址, *(a+1)+1 该行首元素地址+1的地址,*(*(a+1)+1))取得该元素的值。



                return 0;
}         
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-4-10 16:56:22 | 显示全部楼层

回帖奖励 +1 鱼币

int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
printf("%d,%d",a+1,*(a+1));  //既然楼主知道a是二维数组,那么二维数组名代表一个地址,既然是地址怎么能用格式化字符%d来打印输出呢

如果一定要使用二维数组名打印元素,可以这样使用:
#include <stdio.h>
int main ()
{
    int a[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 4; j++)
            printf("%2d ", *((*a + i) + j));
        printf ("\n");
    }
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-10-5 18:34

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表