Defining a pointer to reference the same reference to a variable name?

In objective-c, I really can't figure it out:

void *x = &x;

My understanding:

declare a generic pointer (hence the type void *), the name of the pointer variable is x, and this pointer points to a reference to the variable ( which should be declared already, but it doesn't ). named x.

really confuses me!

+3
source share
3 answers

To conclude if this ad is

 void *x = &x; 

you should consider two important quotes from Standard C.

the first says where the scope of the identifier begins (6.2.1 Identifier areas)

7 Structure, union, and enumeration tags have a scope that begins only after the tag appears in the type specifier that declares the tag. Each enumeration constant has a region that begins immediately after the appearance of its defining enumerator in the list of enumerators. Any other identifier has a scope that begins immediately after the completion of its declarator.

The second one says whether a pointer of any type can be assigned to a pointer to void (6.3.2.3 Pointers)

1 A pointer to void can be converted to or from a pointer to any type of object. A pointer to any type of object can be converted to a pointer to void and vice versa; The result is compared equal to the original pointer.

So in this ad

 void *x = &x; 

the variable x begins immediately before the assignment operator. Its full type is void * , and any pointer of another type can be assigned to it. On the right side there is an expression of type void ** . And according to the second quote, it can be assigned to x, because x is a pointer to void.

As a result, x will save the address by itself.

+5
source

For C and C ++:

x gets its own address. Then he points to himself.

+2
source

Based on the understanding of @alk's answer:

This is exactly the same as you say:

 int y = 10; void* x = &y; 

But in this case, x points to itself instead of y

0
source

Source: https://habr.com/ru/post/1257699/


All Articles