谁能帮我详解一下c语言中数组下标是如何转化成指针的?比如我定义一个数组 int a[5] ={1

谁能帮我详解一下c语言中数组下标是如何转化成指针的?比如我定义一个数组
int a[5] ={1,2,3,4,5};
为什么 a[2] == * (a+2) ;
求详解

所谓指针的概念,和CPU指令中地址的概念是一致的,c语言编译器负责将c语言转化为相应的cpu指令,数组的实现方式就是通过数组的首地址来寻址实现的,因此和指针的概念本质上实现方式是一样的。追问

嗯,大神,我刚接触计算机,也刚接触c语言,有很多不太明白的地方,您可以帮我解释下数组
a[b]== * (a+b)吗?我就是看不懂他们是怎么得来的?

追答

c语言的语法规则就是这样定义的,数组变量a本身就代表指向数组第0个元素的指针,数组元素的存储排列方式也是规定按行序排列的,这个在书上是有清晰的说明的,语法规则就是如此,没有原因。

追问

嗯,a代表的是数组第一个元素指针吧?

您那说数组指向第0个元素指针是打错了吧?

追答

我说的第0个是指c语言的数组下标是从0开始的,我习惯于认为首个是第0个。

为什么要从0开始,还不是对编译器来说计算更方便一点。

追问

嗯,那a+2为什么就可以得到a[2]地址呐

追答

编译器对一维数组下标运算a[b]的解释就是*(a+b),cpu正好就有这种寻址方式,而数组下班则是数学概念。

数组下标是数学概念,cpu没有数组的概念。

追问

嗯,现在对cpu还不了解,希望以后可以慢慢懂,您是怎么知道cpu工作原理的啊?有相关教材吗?

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-06-13
数组名a是数组的首地址,即a[0]的地址,a+2即a[2]的地址,*(a+2)是a[2]的值
所以a[2] == * (a+2)追问

其他的都能看懂,就是(a+2)即a[2]的地址,这里需要详解一下,不懂

追答

按a的类型,比如int型,就是在a的基础上加上2*4(vc中),即为a+2

追问

大神,我刚学到c语言指针,您能讲的通俗易懂点吗?我看不懂啊,“按a的类型,比如int型,就是在a的基础上加上2*4,即为a+2”,您说的在a的基础上加上2*4是什么意思呢?请问

追答

比如a即a[0]的首地址是1000,在vc中,int型是4字节,所以a+2是1000+2*4,即a+2从1008字节开始

追问

为什么a+2就可以得到a[2]的地址了呢?

追答

在编译时,对数组元素a[i]就是按我上面说的进行,即*(a+i)

第2个回答  2015-06-13
规定
表达式 a[b] 的含义被规定为等同于 *(a+b)追问

这个应该可以推出来的吧?

追答

ISO C N1570

6.5.2.1p2

A postfix expression followed by an expression in square brackets [] is a subscripted
designation of an element of an array object. The definition of the subscript operator []
is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that
apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the
initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th
element of E1 (counting from zero).

6.5.6p8

When an expression that has integer type is added to or subtracted from a pointer, the
result has the type of the pointer operand. If the pointer operand points to an element of
an array object, and the array is large enough, the result points to an element offset from
the original element such that the difference of the subscripts of the resulting and original
array elements equals the integer expression.

相似回答