Reputation: 420
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* link;
};
struct Node* A;
int main(){
struct Node* temp = (struct Node*)malloc(sizeof(Node));
temp->data = 2;
temp->link = NULL;
A = temp; // in this line i have doubt
return 0;
}
The doubt is that: A and temp both are pointer to node. A = temp can have two meanings:
So please help me to understand it.
Upvotes: 3
Views: 309
Reputation: 590
First thing first right. How can you assign Null intemp->data = NULL;
here data is int
type.
Your option 1st is correct.
And you have just declared structure pointer variable but not initialized.
Your code had some errors I fixed. Run the code below and see both A and temp have same address after A=temp;
statement which means both are pointing same thing.
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* link;
}; // you had forgot ';' here
struct Node* A;
int main(){
struct Node *temp;
temp=(struct Node*)malloc(sizeof(struct Node));
// this allocates memory and assign its address into temp structure pointer
temp->data = 2;
temp->link = NULL; // here you was doing mistake
A = temp; // in this line i have doubt
printf(" Address of pointer A %p", A);
printf("\n Address of pointer temp is %p",temp);
return 0;
}
Let me know if you have still any doubt.
Upvotes: 1
Reputation: 782295
Assigning a pointer just copies the address, not what the pointer points to. So A = temp;
makes A
and temp
point to the same address.
If you want to copy the elements, you have to dereference the pointers: *A = *temp;
Upvotes: 1