Vaibhav
Vaibhav

Reputation: 33

Why different array dereferencing in printf gives the same output?

Why do all the three print statements give the same output?

#include <stdio.h>

int main(void) {
    int arr[]={1,2,3,4,5};
    printf("%d\n",arr);
    printf("%d\n",&arr);
    printf("%d\n",*(&arr));
    return 0;
}

Upvotes: 3

Views: 67

Answers (1)

dbush
dbush

Reputation: 223917

First, you're "lucky" that all three are printing the same thing because you're using the wrong format specifier to printf. You should be using %p to print a pointer. Using the wrong format specifier invokes undefined behavior.

That being said, all three pointers you're printing have the same value.

In the first statement, you're passing in an array. When passing an array to a function, it decays into a pointer to the first element.

For the second statement, you're taking the address of the array. The address of an array is the same as the address of the first element, so this prints the same value as the first statement.

The third statement first takes the address of the array, yielding a pointer of type int (*)[5], i.e. a pointer to an array of 5 ints. You then dereference this pointer, giving you an array. Like the first statement, this array decays to a pointer to the first element when passed to a function, so this value is the same as the first (as well as the second).

Upvotes: 2

Related Questions