Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Pointer confusion! URGENT!! (http://www.go4expert.com/forums/pointer-confusion-urgent-t10380/)

callmekart 4May2008 17:18

Pointer confusion! URGENT!!
 
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.

listendinesh 6May2008 01:41

Re: Pointer confusion! URGENT!!
 
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);
}


callmekart 6May2008 11:17

Re: Pointer confusion! URGENT!!
 
thanks Dinesh.. it indeed solved the problem!!


All times are GMT +5.5. The time now is 00:48.