10

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

Diego
  • 1,789
  • 10
  • 19
Palace Chan
  • 8,845
  • 11
  • 41
  • 93
  • 1
    Because in the `a` line, `test` is shorthand for `&(test[0])`, and what you are printing out is the fact that the first element of an array has the same address as the whole array. – M.M Feb 17 '15 at 21:54
  • 5
    possible duplicate of [How come an array's address is equal to its value in C?](http://stackoverflow.com/questions/2528318/how-come-an-arrays-address-is-equal-to-its-value-in-c) – R Sahu Feb 17 '15 at 21:58
  • 1
    I'm not really a fan of closing C++ questions as duplicates of C questions (even if the principle is the same in both languages) – M.M Feb 17 '15 at 22:36

1 Answers1

6

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.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264