Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C/C++, for an array a, I just learned that (void*)&a == (void*)a. How does that work?

So, I always knew that the array "objects" that are passed around in C/C++ just contained the address of the first object in the array.

How can the pointer to the array "object" and it's contained value be the same?

Could someone point me towards more information maybe about how all that works in assembly, maybe.

like image 704
Jules G.M. Avatar asked Nov 26 '12 02:11

Jules G.M.


People also ask

Can you have an array of void in C?

In C, it is possible to have array of all types except following. 1) void. 2) functions. But we can have array of void pointers and function pointers.

What does void star mean in C?

A void pointer(void* ) is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typcasted to any type.

Can an array be void?

You can't have a variable of type void (or an array of void ) for the simple reason that there are no values of type void for it to hold.

How do you declare an array in C?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100};


1 Answers

Short answer: A pointer to an array is defined to have the same value as a pointer to the first element of the array. That's how arrays in C and C++ work.

Pedantic answer:

C and C++ have rvalue and lvalue expressions. An lvalue is something to which the & operator may be applied. They also have implicit conversions. An object may be converted to another type before being used. (For example, if you call sqrt( 9 ) then 9 is converted to double because sqrt( int ) is not defined.)

An lvalue of array type implicitly converts to a pointer. The implicit conversion changes array to &array[0]. This may also be written out explicitly as static_cast< int * >( array ), in C++.

Doing that is OK. Casting to void* is another story. void* is a bit ugly. And casting with the parentheses as (void*)array is also ugly. So please, avoid (void*) a in actual code.

like image 112
Potatoswatter Avatar answered Oct 12 '22 00:10

Potatoswatter