-1
struct Data
{
    int num;
    struct *next, *prev;
};

typedef struct Data sData;

int main()
{
    sData *head;
    head = NULL;
    printf("%lld %lld", head, &head);
    return 0;
}

I am trying to understand deeper about struct pointers and their memory allocations. Why do the printed values differ?

Yuankun
  • 6,875
  • 3
  • 32
  • 34
Bernard Wijaya
  • 112
  • 1
  • 5
  • 1
    `head` gives you the value of the un-initialized pointer, what is undefined behavior. `&head` gives you the address of your variable `head`. Why should value and address be the same? – harper Apr 25 '18 at 15:07
  • 1
    also, its better to use `%p` to print pointers, check https://stackoverflow.com/questions/9053658/correct-format-specifier-to-print-pointer-address – Iłya Bursov Apr 25 '18 at 15:08
  • 1
    _Why is the printed value differ ?_ because `head` and `&head` are not same. when you print `head` it print what it contains which is `NULL` and when you print address of `head` it prints address . – Achal Apr 25 '18 at 15:08
  • sorry I forgot to Initialized it as NULL – Bernard Wijaya Apr 25 '18 at 15:09
  • 1
    `printf("%lld %lld", head, &head);` is not a well defined way to print 2 pointers. Suggest `printf("%p %p\n", (void*) head, (void*) &head);` instead and report you findings. – chux - Reinstate Monica Apr 25 '18 at 15:28

2 Answers2

1

Looking at your code, head is a variable. The fact that it is a pointer on SData structure is not useful to understand:

  • head returns the value of the variable head, here it is NULL.
  • &head returns the address of the variable head, here it depends on your compiler and linker configuration. As head is a local variable, it may be an address of a location in the stack.
Laurent H.
  • 6,316
  • 1
  • 18
  • 40
1

Printing "head" you can see the address of memory block where it's pointing (NULL), and printing "&head" you see the adress of memory block where the "head" variable is stored.

Bruno
  • 139
  • 1
  • 8