二維數組指針問題
一个二维数组int a={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);
為什麼不行,而且值也很奇怪
从编译出现警告其实就比较容易知道了。
你操作类型不同,一个是数组指针,一个是指针。
test.c: In function ‘main’:
test.c:8:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int (*)’ [-Wformat=]
8 | printf("%d,%d\n",a+1,*(a+1));
| ~^ ~~~
| | |
| int int (*)
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 (*)’ [-Wformat=]
10 | printf("%d,%d",a+1+2,*(a+1)+2);
| ~^ ~~~~~
| | |
| int int (*)
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 #include <stdio.h>
int main()
{
int a={1,2,3,4,
5,6,7,8,9,
10,11,12};
int *p = a; // 指针变量
printf("%d\n ",*(p+1)); // 指针变量
printf("%d\n",*(*(a+1)+1)); // 二维数组指针索引。 a+1 定们到行, *(a+1) 该行首元素地址, *(a+1)+1 该行首元素地址+1的地址,*(*(a+1)+1))取得该元素的值。
return 0;
} int a={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 = {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;
}
页:
[1]