0

This is the def of my structure

    typedef struct treeNode
     {
        int data,pos;
        char name[16];
        struct treeNode *left;
        struct treeNode *right;
     }treeNode;

I have created an dynamic object

treeNode *temp;
            temp = (treeNode *)malloc(sizeof(treeNode));

If I have to assign a value to data how should I assign

scanf("%d",temp->data);   //or
scanf("%d",&(temp->data)); //why? because all scanf will look for is address to a location which could be done by temp->data;

and this goes for accessing data also i.e. how should I access the integer part ?

temp->data; //or
*(temp->data) 
xaxxon
  • 19,189
  • 5
  • 50
  • 80
Amit Gupta
  • 277
  • 1
  • 2
  • 9

2 Answers2

2

scanf("%d",&temp->data);

Because scanf() needs address of variable. For each conversion specifier, scanf() expects the corresponding argument to be a pointer to the proper type: %d expects an argument of type int *, %f expects an argument of type double *, %c and %s both expect an argument of type char *, etc.

Behaviour of scanf() gives more idea about scanf().

for accessing temp->data is enough, because it is essentially equivalent to (*temp).data.

If you try to access *(temp->data) then you trigger undefined behaviour. Because, you are accessing a memory location which may be in other process's context.

say temp->data is 100, then *(temp->data) means *(100), i.e accessing at memory location 100.

Community
  • 1
  • 1
Jeyaram
  • 9,158
  • 7
  • 41
  • 63
0

Whenever you want to set the value of a parameter that is passed into a function, you need to send in the address. Since you want scanf to populate the value of that parameter, you need to use the address. (Note that if the struct element is already a pointer (with memory allocated to it), you wouldn't need the &).

However, when you want to read something, there is no need to use the address. You can just use it directly.

xaxxon
  • 19,189
  • 5
  • 50
  • 80
  • in case of assigning like temp->data the behaviour is undefined.In my case i'm getting a run time error of "access violation" which I was xpecting not to occur earlier.So I want to clearify things. – Amit Gupta Dec 05 '12 at 06:44
  • It's trying to treat whatever value is in temp->data as a pointer. That's almost always going to point to memory not associated with the process, so you're going to have access violations. – xaxxon Dec 05 '12 at 07:10