Thread: Why program print two different locations

  1. #1
    Registered User
    Join Date
    Feb 2022
    Posts
    73

    Why program print two different locations

    In program I am expecting address of 'new' and address of first member sould be same

    Code:
    #include<stdio.h>
    
    #include<stdlib.h>
    
    
    struct node 
    {
        int data;
        struct node *next;
    };
    
    
    struct node *Add( struct node * Head, int value)
    {
        struct node * new = malloc(sizeof(*new));
        printf("addresses of a new : %p \n", (void*)&new);    
        
        if( new != NULL )
        {
            new -> data = value;
            printf("addresses of first member : %p \n", (void*)&new->data);
            new -> next = NULL;
        }
    
    
     return new; 
    }    
    
    
    int main ()
    {
        struct node * head = NULL ;    
        head = Add( head, 1);
        return 0;
    }
    When I run code I don't understand why I get difffferent value

    addresses of a new : 0061FEEC
    addresses of first member : 00C10D18

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,308
    > printf("addresses of a new : %p \n", (void*)&new);
    You're printing the address of your local variable.

    Not the result of the malloc call.

    Use
    printf("addresses of a new : %p \n", (void*)new);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Feb 2022
    Posts
    73
    Quote Originally Posted by Salem View Post
    > printf("addresses of a new : %p \n", (void*)&new);
    You're printing the address of your local variable.

    Not the result of the malloc call.

    Use
    printf("addresses of a new : %p \n", (void*)new);
    'new' is local variable that hold memory location but what's memory address of new where it is stored. Is 0061FEEC address of new where it hold memory location of other variable

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Tictactoe x and o locations.
    By xTonyLeo in forum C Programming
    Replies: 10
    Last Post: 01-27-2013, 06:12 PM
  2. New pointer locations
    By mica in forum C Programming
    Replies: 2
    Last Post: 03-23-2011, 08:31 AM
  3. program to print itself
    By ElemenT.usha in forum C Programming
    Replies: 6
    Last Post: 02-09-2008, 05:12 AM
  4. file i/o locations
    By algi in forum C++ Programming
    Replies: 4
    Last Post: 01-16-2005, 11:21 AM
  5. C++ program to print itself
    By Unregistered in forum C++ Programming
    Replies: 3
    Last Post: 11-27-2001, 02:25 PM

Tags for this Thread