Reputation: 201
In this code, the variable temp
is reusable (in while loop) and can be used to allocate memory again and again without any error. Is it normal functioning?
#include<stdio.h>
#include<stdlib.h>
struct node{
int i;
struct node *next;
};
int main()
{
struct node *head,*temp;
char c;
printf("Do you want to enter data? Y/N ");
scanf(" %c",&c);
if((c=='Y')||(c=='y'))
{
head=malloc(sizeof(struct node));
head->next=NULL;
printf("Please enter your data: ");
scanf(" %d",&head->i);
}
printf("Do you want to enter data? Y/N ");
scanf(" %c",&c);
while((c=='Y')||(c=='y')) //LOOK INTO THIS LOOP
{
temp=malloc(sizeof(struct node));
temp->next=head;
printf("Please enter your data: ");
scanf(" %d",&temp->i);
head=temp;
printf("Do you want to enter data? Y/N ");
scanf(" %c",&c);
}
return 0;
}
Upvotes: 1
Views: 855
Reputation: 51
yes, your code is normal, since you are assigning 'temp' to 'head' pointer in while(), so that you will not lose your address and you can again use 'temp' for creating memory for new structure. If you have not assign 'temp' to 'head' then it will lead you to danger.because once you allocate memory for new structure 'temp' will point to that structure and previous structure address you will lose even if structure is there but you will not be able to find it.Same code you can optimize and write like this.
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int i;
struct node *next;
}NODE;
int main()
{
NODE *head=NULL;
NODE *tmp;
char c;
do{
tmp=malloc(sizeof(NODE));
printf("enter the number\n");
scanf("%d",&tmp->i);
tmp->next=head;
head=tmp;
printf("Do you want to enter another number\n");
scanf(" %c",&c);
}
while(c=='y' ||c=='Y');
printf("entered numbers are \n");
while(head)
{
printf("%d\t",head->i);
head=head->next;
}
}
Upvotes: 0
Reputation: 93524
It is entirely normal, temp
is not the memory allocated, it is simply a pointer to the allocated memory; that pointer-value can be copied to another pointer-variable and that pointer-variable may then be used to access the same allocated memory and also to later de-allocate it. Moreover it does not matter how many times the pointer is copied, it is the pointer-value not the specific pointer-variable that is necessary for memory access and management.
The pointer value in temp
is copied to head
to add the item to the list; similarly before that, the previous head
is copied to head->next
to maintain the links. Presumably elsewhere in the code when a entry is removed from the list, the value in head
is used to un-link the head element and free the allocated memory; something like:
temp = head ; // Copy current head pointer
head = head->next ; // Remove head from the list
free(temp) ; // Deallocate removde list item
Upvotes: 2