In an array, what does &arr[2] return?
If we have an array[5], we know that arr == &开发者_StackOverflowarr[0] but what is &arr[2] = ?
Also, what does &arr return to us?
In c, the only difference between []
operator and the +
operator is that the []
operator also dereferences the pointer. This means that arr[2] == *(arr + 2)
, and &arr[2] == &(*(arr + 2)) == arr + 2
.
On a side note, this also means the fun interaction wherein you reference array indexes like index[array]
: that is, arr[2] == 2[arr]
.
The more you know....
Let's look at a simple example first:
int a;
a = 5;
In a sense the integer a has two values assoicated with it. The one you most likely think about first is the rvalue, which in this case is the number 5. There is also what is called an lvalue (pronounced "el value") which is the memory address the integer a is located at.
This is an important concept to grasp. At the end of the day everything is all about memory. We store code and variables in memory. The CPU executes instructions which are located in memory and it performs actions on data which is also in memory. It's all just memory. Nothing very complicated; if someone tries to scare you with pointers don't listen, it's all just memory :)
Alrighty so, in the case of an array we are dealing with a contiguious block of memory that is used for storing data of the same type:
int array[] = {0, 1, 1, 2, 3, 5, 8, 13, 21};
As you have already noted the name of the array refers to the memory location of the first element in the array (e.g. array == &array[0]). So in my example array above &array[2] would refer to the memory location (or lvalue) that contains the third element in the array.
To answer your other question &array is just another memory address, see if this code snippet helps clear up what it points to :)
#include <stdio.h>
#include <stdlib.h>
int array[] = {0, 1, 1, 2, 3, 5, 8, 13, 21};
int main(void) {
printf("&array[2] is: %p\n", &array[2]);
printf("&array[0] is: %p\n", &array[0]);
printf("&array is: %14p\n", &array);
exit(0);
}
% gcc test.c
% ./a.out
&array[2] is: 0x100001088
&array[0] is: 0x100001080
&array is: 0x100001080
If we have an array[5], we know that arr = &arr[0] but what is &arr[2] = ?
In a C based language, &arr[0]
is a pointer to the first element in the array while &arr[2]
is a pointer to the third element in the array. Arrays decay into pointers to the first element, so in certain context array
and &arr[0]
are actually the same thing: a pointer to the first element.
&arr[0] == arr + 0
&arr[1] == arr + 1
&arr[2] == arr + 2
and so on.
In both C and C++, if T
is a fundamental type, and you have an array T array[N]
, then array[i]
is *(array+i)
, using the fact that the expression array
decays to a pointer type in an expression.
精彩评论