为什么数组名是指向数组第一个元素的指针? [英] why is array name a pointer to the first element of the array?

查看:54
本文介绍了为什么数组名是指向数组第一个元素的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是否总是如此,我的意思是,数组名称始终是指向数组第一个元素的指针.为什么会这样?它是某种实现方式还是某种语言功能?

Is this always the case , i mean , that array name is always a pointer to the first element of the array.why is it so?is it something implementation kinda thing or a language feature?

推荐答案

数组名本身不是一个指针,但在大多数上下文中会衰减为指向数组第一个元素的指针.之所以这样,是因为语言是这样定义的.

An array name is not itself a pointer, but decays into a pointer to the first element of the array in most contexts. It's that way because the language defines it that way.

来自 C11 6.3.2.1 左值、数组和函数指示符,第 3 段:

From C11 6.3.2.1 Lvalues, arrays, and function designators, paragraph 3:

除非它是 sizeof 运算符、_Alignof 运算符或一元 & 运算符,或者是用于初始化数组的字符串字面量,将类型为type 数组"的表达式转换为表达式类型为pointer to type",指向数组对象的初始元素,不是左值.

Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue.

您可以从 数组和指针comp.lang.c 常见问题解答的 a> 部分.

You can learn more about this topic (and lots about the subtle behaviour involved) from the Arrays and Pointers section of the comp.lang.c FAQ.

编辑旁白:同样的行为发生在 C++ 中,尽管语言对它的指定有点不同.作为参考,来自我这里的 C++11 草案,4.2 数组到指针的转换,第 1 段:

Editorial aside: The same kind of behaviour takes place in C++, though the language specifies it a bit differently. For reference, from a C++11 draft I have here, 4.2 Array-to-pointer conversion, paragraph 1:

N T 的数组"或T 的未知边界数组"类型的左值或右值可以转换为指向 T 的指针"类型的右值.结果是指向数组第一个元素的指针.

An lvalue or rvalue of type "array of N T" or "array of unknown bound of T" can be converted to an rvalue of type "pointer to T". The result is a pointer to the first element of the array.

这篇关于为什么数组名是指向数组第一个元素的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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