Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of first element in static declaration of array

Tags:

c

int main()
{
    int a[3]={1,10,20};
    printf("%u %u %u \n" ,&a,a,&a[0]);
    return 0;
}

This prints the same value for all three. I understand that a and &a[0] is same but how is &a also same?

like image 886
Divij Avatar asked Jun 24 '11 19:06

Divij


People also ask

How a static array is declared?

Statically declared arrays are allocated memory at compile time and their size is fixed, i.e., cannot be changed later. They can be initialized in a manner similar to Java. For example two int arrays are declared, one initialized, one not. Static multi-dimensional arrays are declared with multiple dimensions.

Which refers to the first element in an array?

first element of an array will be arr[0] which is value of arr[0] and. array means arr and arr names represents base address of the array.

What is the address of the array?

The address of an array is the address of its first element, which is the address of the first byte of memory occupied by the array. A picture can help illustrate this. Let's say we declare an array of six integers like this: int scores[6] = {85, 79, 100, 92, 68, 46};


3 Answers

For maximum compatibility you should always use %p and explicitly cast to void* to print pointer values with printf.

When the name of an array is used in an expression context other than as the operand to sizeof or unary & it decays to a pointer to its first element.

This means that a and &a[0] have the same type (int*) and value. &a is the address of the array itself so has type int (*)[3]. An array object starts with its first element so the address of the first element of an array will have the same value as the address of the array itself although the expressions &a[0] and &a have different types.

like image 54
CB Bailey Avatar answered Oct 27 '22 19:10

CB Bailey


My C is rusty, but so far as I know, &a is the address of the beginning of the array, which will correspond exactly to &a[0] since the beginning of the array IS the first element.

Again, rusty with C so I'll defer to someone with better expertise.

like image 24
Nick Coelius Avatar answered Oct 27 '22 18:10

Nick Coelius


The fact that &a happens to be the same as a in this case is a consequence of the fact that a is statically sized. If you made a a pointer to an array, then it would be a different number while the other two gave you the same result.

For example:

int main()
{
    int b[3]={1,10,20};
    int* a = b;
    printf("%u %u %u \n" ,&a,a,&a[0]);
    return 0;
}

An example output is:

2849911432 2849911408 2849911408

like image 43
Mikola Avatar answered Oct 27 '22 17:10

Mikola