0
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

struct node
{
    int id;
    struct node *next;
};
typedef struct node NODE;
int main()
{
    NODE *hello;        
    hello=(NODE *) malloc(sizeof(NODE));
    hello->id=5;
    printf("\nAfter malloc\n");
    printf("address of hello: %d ",hello);
    printf("\n");
    printf("Value of Id is: %d , Value of next is: %u\n",hello->id,hello->next);
    return 0;
}

I tried to execute the above code, I got the following output.

Output:

After Malloc

address of hello: 16949264

Value of Id is:5, value of next is: 0

My question is, why the value of hello is not assigned to next?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Lokesh Sanapalli
  • 1,012
  • 3
  • 18
  • 39

2 Answers2

0

why the value of hello is not assigned to next?

Why it should be? You've assigned the memory to hello, so it has a value. next is not allocated memory yet, so it does not show any value. (To be truthful, it is indeterminate).

Also, to print an address, you should be using the %p format specifier with printf() and cast the corresponding argument to (void *).

Also, Please see this discussion on why not to cast the return value of malloc() and family in C..

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Thank you for your response, I have a doubt, when will the memory will be allocated for structure at the time of declaring or when the variable is created for it? – Lokesh Sanapalli Sep 25 '15 at 07:49
  • @lokesh1729 the memory for the pointer variable is allocated, the memory to the pointer (to which it will point) needs to be allocated. – Sourav Ghosh Sep 25 '15 at 07:50
  • @lokesh1729 try printing `(void *)&(hello->next)` and see for yourself. – Sourav Ghosh Sep 25 '15 at 07:51
  • NODE *hi; printf("\nbefore malloc\n"); printf("\naddress of node is: %p",(void *)hi); printf("\naddress of next is: %p",(void *)hi->next); – Lokesh Sanapalli Sep 25 '15 at 07:56
  • I got the output like this before malloc address of node is: 0x7ffda77a81b0 address of next is: 0x7ffda77aa470 here why the address of node and next is different, next should store the address of node – Lokesh Sanapalli Sep 25 '15 at 07:59
0

hello->next is not hello, so the value of hello is not assigned to hello->next.

hello->next is not hello->value, either, so hello->value is not assigned to hello->next.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70