数组名是指针吗? [英] Is an array name a pointer?

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

问题描述

数组名在 C 中是指针吗?如果不是,数组名和指针变量有什么区别?

Is an array's name a pointer in C? If not, what is the difference between an array's name and a pointer variable?

推荐答案

数组是数组,指针是指针,但在大多数情况下,数组名称会转换为指针.一个经常使用的术语是它们衰减到指针.

An array is an array and a pointer is a pointer, but in most cases array names are converted to pointers. A term often used is that they decay to pointers.

这是一个数组:

int a[7];

a 包含七个整数的空间,您可以通过赋值将一个值放入其中一个,如下所示:

a contains space for seven integers, and you can put a value in one of them with an assignment, like this:

a[3] = 9;

这是一个指针:

int *p;

p 不包含任何整数空格,但它可以指向一个整数空格.例如,我们可以将其设置为指向数组 a 中的一个位置,例如第一个:

p doesn't contain any spaces for integers, but it can point to a space for an integer. We can, for example, set it to point to one of the places in the array a, such as the first one:

p = &a[0];

令人困惑的是,您也可以这样写:

What can be confusing is that you can also write this:

p = a;

不会将数组a的内容复制到指针p中(不管这意味着什么).相反,数组名称 a 被转换为指向其第一个元素的指针.所以这个任务和上一个任务一样.

This does not copy the contents of the array a into the pointer p (whatever that would mean). Instead, the array name a is converted to a pointer to its first element. So that assignment does the same as the previous one.

现在您可以像使用数组一样使用 p:

Now you can use p in a similar way to an array:

p[3] = 17;

这样做的原因是 C 中的数组解引用运算符 [ ] 是根据指针定义的.x[y] 表示:从指针 x 开始,在指针指向的元素之后向前步进 y 元素,然后取任何存在的元素.使用指针算术语法,x[y]也可以写成*(x+y).

The reason that this works is that the array dereferencing operator in C, [ ], is defined in terms of pointers. x[y] means: start with the pointer x, step y elements forward after what the pointer points to, and then take whatever is there. Using pointer arithmetic syntax, x[y] can also be written as *(x+y).

为了使用普通数组,例如我们的 a,必须首先转换 a[3] 中的名称 a指向一个指针(指向 a 中的第一个元素).然后我们将 3 个元素向前推进,并采用那里的任何元素.换句话说:取数组中位置 3 处的元素.(这是数组中的第四个元素,因为第一个元素编号为 0.)

For this to work with a normal array, such as our a, the name a in a[3] must first be converted to a pointer (to the first element in a). Then we step 3 elements forward, and take whatever is there. In other words: take the element at position 3 in the array. (Which is the fourth element in the array, since the first one is numbered 0.)

所以,总而言之,C 程序中的数组名称(在大多数情况下)转换为指针.一个例外是当我们在数组上使用 sizeof 运算符时.如果 a 在此上下文中被转换为指针,sizeof a 将给出指针的大小而不是实际数组的大小,这将是无用的,因此case a 表示数组本身.

So, in summary, array names in a C program are (in most cases) converted to pointers. One exception is when we use the sizeof operator on an array. If a was converted to a pointer in this context, sizeof a would give the size of a pointer and not of the actual array, which would be rather useless, so in that case a means the array itself.

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

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