Pointer confusion! URGENT!!

callmekart's Avatar, Join Date: May 2008
Newbie Member
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 shabbir; 4May2008 at 17:54.. Reason: Code block
0
listendinesh's Avatar, Join Date: Aug 2007
Go4Expert Member
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);
}
0
callmekart's Avatar, Join Date: May 2008
Newbie Member
thanks Dinesh.. it indeed solved the problem!!