Palace Chan
Palace Chan

Reputation: 9183

Why does dereferencing an array or not result in the same address?

In C++, I wrote the following simple main:

int main() {
    char test[100];
    void* a = (void*) test;
    void* b = (void*) &test;

    std::cout << a << " " << b << std::endl;

    return 0;
}

And it gives me the same result for a and b. Why is this? I would expect from the notation that the second be the address of the first..

Upvotes: 10

Views: 175

Answers (1)

haccks
haccks

Reputation: 106012

In C++, arrays are converted to pointer to first element of the array. test is pointer to first element test[0]. &test is the address of entire array test. Although, the type of test and &test are different, their values are same and that's why you are getting the same value.

For example

int a[3] = {5, 4, 6};  

Look at the diagram below:

enter image description here

For detailed explanation read this answer.

Upvotes: 6

Related Questions