I'm having some trouble understanding the advantages and disadvantages of using scanf over fgets.
When we have allocated memory using an array for eg, it is not wise to use scanf since buffer overflow can occur. But in what way does fgets prevent that from happening?
Also, if you are allocating memory dynamically then is it okay to be using scanf?
I have this code:
typedef struct node
{
int data;
struct node *next;
}NODE;
static NODE *find(NODE *element);
void main()
{
NODE *element,*head,*a;
element = (NODE *) malloc (sizeof(NODE));
element->next=head;
printf("Enter the data\n");
scanf("%d",&element->data);
head=element;
a =find(element);
if(a)
{
printf("Element %d was found \n",element->data);
}
else
{
printf("Element %d was not found\n",element->data);
}
free(head);
}
NODE * find(NODE *element)
{
while(element)
{
if(element->data==50)
{
return element;
}
else
{
return 0;
}
element=element->next;
}
}
If I were to use fgets instead of scanf here, how would I incorporate it?
Thanks.