Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

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..

like image 721
Palace Chan Avatar asked Feb 17 '15 21:02

Palace Chan


1 Answers

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.

like image 60
haccks Avatar answered Oct 20 '22 09:10

haccks