1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Pointer confusion! URGENT!!

Discussion in 'C' started by callmekart, May 4, 2008.

  1. callmekart

    callmekart New Member

    Joined:
    May 4, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    Hi I have got stuck bcos of this unexpected result .. Can someone Aid???

    Program:
    Code:
    #include <stdio.h>
    
    typedef struct tStruct
    {
        int a;
        int b;
        int c;
    }tStruct;
    
    tStruct *temp1;
    
    void func1(tStruct *node)
    {
    
        temp1 = (tStruct*)malloc(sizeof(tStruct));
        printf("\n Address of the node : %u",temp1);
    
        node = temp1; // I doubt this part.
        node->a = 1;
        node->b = 2;
        node->c = 3;
        printf("\n Value of a : %u",temp1->a);
        printf("\n Value of b : %u",temp1->b);
        printf("\n Value of c : %u",temp1->c);
    }
    
    main()
    {
        tStruct *temp=0;
        func1(temp);
        printf("\n Address of the node : %u",temp);
        printf("\n Value of a : %u",temp->a);
        printf("\n Value of b : %u",temp->b);
        printf("\n Value of c : %u",temp->c);
    }
    Result:

    Address of the node : 2500
    Value of a : 1
    Value of b : 2
    Value of c : 3
    Address of the node : 0
    Value of a : 0
    Value of b : 0
    Value of c : 30036

    I need to view the values of the the node in the main() function. But am unsuccessful.

    Thanks in Advance.

    Cheers,
    Kart.
     
    Last edited by a moderator: May 4, 2008
  2. listendinesh

    listendinesh New Member

    Joined:
    Aug 3, 2007
    Messages:
    18
    Likes Received:
    0
    Trophy Points:
    0
    Hi,
    From main you are passing temp by value, to achieve desired result you should pass temp by address.
    Like
    Code:
    #include <stdio.h>
    
    typedef struct tStruct
    {
        int a;
        int b;
        int c;
    }tStruct;
    
    tStruct *temp1;
    void func1(tStruct **node)
    {
    
        temp1 = (tStruct*)malloc(sizeof(tStruct));
        printf("\n Address of the node : %u",temp1);
    
        *node = temp1; // I doubt this part.
        (*node)->a = 1;
        (*node)->b = 2;
        (*node)->c = 3;
        printf("\n Value of a : %u",temp1->a);
        printf("\n Value of b : %u",temp1->b);
        printf("\n Value of c : %u",temp1->c);
    }
    
    
    main()
    {
        tStruct *temp=0;
        func1(&temp);
        printf("\n Address of the node : %u",temp);
        printf("\n Value of a : %u",temp->a);
        printf("\n Value of b : %u",temp->b);
        printf("\n Value of c : %u",temp->c);
    }
    
     
  3. callmekart

    callmekart New Member

    Joined:
    May 4, 2008
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    thanks Dinesh.. it indeed solved the problem!!
     

Share This Page