cpointersself-referenceconstruct

Why self-referential struct in C output is nill


I want to create a structure in C and I want it to have only one component which will be its address.

In other words I just create a one component self-referential struct:

#include <stdio.h>
#include <string.h>
 
struct Books {
   struct Books *ptr; //* the only one component of this structure*//
};

int main( ) {
    struct Books book1;
    printf("%p\n", book1.ptr);
    
    return 0;
}

The output of this script is - nil.

And my question is - why ? This script has created in computer memory physical entry where the one component struct- book1 is recorded.

Now I want to see the address of this struct (or to say in different words I want to see content of this one-component struct).

Once it physically exists why does it give me output nill ?


Solution

  • Try this:printf("%p\n", &book1); for printing the address of the struct. You are trying to print out an uninitialized value and the programm has undefined behavior. Use & to print addresses