uditkumar01
uditkumar01

Reputation: 420

problem-related to structures and pointers in C

#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:

  1. We are copying the address of temp in A, hence A will point to the same address.(means both of them are same identities/variables)
  2. We are copying the elements of temp and assigning it to elements of A.(means both of them are separate identities/variables). We generally do this in structures.

So please help me to understand it.

Upvotes: 3

Views: 309

Answers (2)

Ankit Mishra
Ankit Mishra

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

Barmar
Barmar

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

Related Questions