Andy Lin
Andy Lin

Reputation: 447

the value of a variable or expression of type array is the address of element zero of the array

I'm reading K&R programming language 2ed. In section 5.3(page 99):

By definition, the value of a variable or expression of type array is the address of element zero of the array.

It tells us that if I declare an array:

int arr[3];

The value of arr is a default value of address of the first element of array.

I tried to set a experiment in gcc that:

int arr[3] = {0, 1, 2};
printf("%p",arr);

The output is still the address of the first element of array, although I've changed it to 0.

Why?

Upvotes: 1

Views: 191

Answers (2)

CoderX
CoderX

Reputation: 162

That is because the variable arr is a pointer itself having the address to the first element of {0, 1, 2}

It would be equivalent to do this:

int a = 0;
int b = 1;
int c = 2;

printf("%p", &a);

The %p prints the address a pointer is pointing too. (I know, it sounds confusing)

Upvotes: 1

Harlan Wagner
Harlan Wagner

Reputation: 46

The printf specifier %p will print the actual memory address of arr, which contains the value of the first element of the array.

The following code will dereference the pointer and print the value contained in the memory locaction pointed to by arr.

printf("%u\n", *arr);

The syntax:

printf("%u\n", arr[0]);

Will also dereference the array pointer, if that is what you are interested in.

Upvotes: 1

Related Questions