为什么是一个数组变量一样本身的地址? [英] Why is address of an array variable the same as itself?

查看:127
本文介绍了为什么是一个数组变量一样本身的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C,如果我们有像 A [10] ,那么 A 和<$ C $数组C>&放大器;一个具有相同的指针值(但不是同一类型)。我想知道为什么为:C这样设计?

对您节省存储&放大器所需的额外空间;一个? ......这是有道理的,当你认为的事实,即 A 不能指向任何其他位置,因此存储&放大器;一个是没有意义的。


解决方案

  

事实上, A 不能指向任何其他位置


这是不是事实,虽然。如果 A 是一个数组, A 不指向任何地方,因为 A 不是一个指针。鉴于 int类型的[42]; A 名42数组 INT 对象;它不是一个指针,42 INT 对象的数组(这将是 INT(*一)[42]; )。

&放大器; X 给你的对象的地址x ;如果 X 是一个数组类型的变量,那么&放大器; X 为您提供了数组的地址;如果不出意外,这与&放大器的行为是一致的。用于其他任何目的。

有一个更好的问题将是为什么一个数组(如 A )衰减到一个指向其初始元素在大多数情况下,当它被使用?虽然我不能肯定知道你为什么语言的目的是这样,它确实让很多事情变得简单规范,值得注意的是,有一个数组运算实际上是同一个指针运算。

In C, if we have an array like a[10], then a 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 that a can never point to any other location, so storing &a is meaningless.

解决方案

the fact that a can never point to any other location

This isn't a fact, though. If a is an array, a doesn't point anywhere because a is not a pointer. Given int a[42];, a names an array of 42 int objects; it is not a pointer to an array of 42 int objects (that would be int (*a)[42];).

&x gives you the address of the object x; if x 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆