Siddhartha - 1 year ago 123
C Question

# In an array, what does &arr[2] return?

If we have an array[5], we know that arr == &arr[0]
but what is &arr[2] = ?

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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download