为什么在2D数组中a和* a指向相同的地址? [英] Why in a 2D array a and *a point to same address?
本文介绍了为什么在2D数组中a和* a指向相同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想学习2D数组的实现方式以及内存分配的方式.所以我在给定的c程序中有些疑问,为什么a和* a给出相同的地址.
I am just trying to learn how 2D arrays implemented and how memory allocation takes place. so I get some doubt in the given c program that why a and *a giving same address.
#include<stdio.h>
main()
{
int i,j;
int a[3][3]={1,2,3,4,5,6,7,8,9};
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d\t",*(*(a+i)+j));
}
printf("\n");
}
printf("%d\n",a);
printf("%d\n",a[0]+1);
printf("%d\n",a[0][0]);
printf("%d\n",a+1);
printf("%d\n",*a);
}
这是输出
推荐答案
一种了解2D数组的直观方法就是这样...
A visual way to understand the 2D array is like this...
a --> a[0] --> [1,2,3]
a[1] --> [4,5,6]
a[2] --> [7,8,9]
a [0],a [1],a [2]是逻辑表示,而不是实际的内存.
a[0], a[1], a[2] are logical representation and not actual memory.
so a[0] = a + 0*[bytes occupied by one row],
a[1] = a + 1*[bytes occupied by one row],
a[2] = a + 2*[bytes occupied by one row]
因此*a => a[0] => a
请注意,即使地址相同,当我们调用a
与a[0]
或*a
时,指针的类型"也会更改.通过(a + 1)和(a [0] +1)的打印输出可以很容易地看到这一点.
Note that even though the address is same the "type" of pointer changes when we invoke a
vs a[0]
or *a
. This can be easily seen by your print output of (a+1) and (a[0]+1).
这篇关于为什么在2D数组中a和* a指向相同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文