为什么是一个数组变量一样本身的地址? [英] Why is address of an array variable the same as itself?
问题描述
在C,如果我们有像 A [10]
,那么 A
和<$ C $数组C>&放大器;一个具有相同的指针值(但不是同一类型)。我想知道为什么为:C这样设计?
对您节省存储&放大器所需的额外空间;一个
? ......这是有道理的,当你认为的事实,即 A
不能指向任何其他位置,因此存储&放大器;一个
是没有意义的。
事实上,
A
不能指向任何其他位置
块引用>这是不是事实,虽然。如果
A
是一个数组,A
不指向任何地方,因为A
不是一个指针。鉴于int类型的[42];
,A
名42数组INT
对象;它不是一个指针,42INT
对象的数组(这将是INT(*一)[42];
)。
&放大器; X
给你的对象的地址x
;如果X
是一个数组类型的变量,那么&放大器; X
为您提供了数组的地址;如果不出意外,这与&放大器的行为是一致的。
用于其他任何目的。有一个更好的问题将是为什么一个数组(如
A
)衰减到一个指向其初始元素在大多数情况下,当它被使用?虽然我不能肯定知道你为什么语言的目的是这样,它确实让很多事情变得简单规范,值得注意的是,有一个数组运算实际上是同一个指针运算。In C, if we have an array like
a[10]
, thena
and&a
have the same pointer value (but not the same type). I want to know why was C designed like this?Was this to save the additional space required for storing
&a
? ... This makes sense when you think of the fact thata
can never point to any other location, so storing&a
is meaningless.解决方案the fact that
a
can never point to any other locationThis isn't a fact, though. If
a
is an array,a
doesn't point anywhere becausea
is not a pointer. Givenint a[42];
,a
names an array of 42int
objects; it is not a pointer to an array of 42int
objects (that would beint (*a)[42];
).
&x
gives you the address of the objectx
; ifx
is an array type variable, then&x
gives you the address of the array; if nothing else, this is consistent with the behavior of&
for any other object.A better question would be "why does an array (like
a
) decay to a pointer to its initial element in most cases when it is used?" While I don't know with certainty why the language was designed this way, it does make the specification of many things much simpler, notably, arithmetic with an array is effectively the same as arithmetic with a pointer.这篇关于为什么是一个数组变量一样本身的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!