P
pereges
have i written this program correctly ?
it is giving me correct output but i am little suspicious in the
following two statements -
scanf("%d", &ptr->data) and printf("%d\n", ptr->data).
/********** LINK LIST **********/
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s
{
void *data;
struct node_s *next;
}node;
int add_to_link_list(node **head)
{
node *ptr;
int temp;
ptr = malloc(sizeof(node));
if (ptr == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}
ptr->data = malloc(sizeof(int));
if (ptr->data == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}
printf("Enter data\n");
if (scanf("%d", &ptr->data) != 1)
{
fprintf(stderr, "Error while entering data\n");
return (1);
}
ptr->next = *head;
*head = ptr;
return (0);
}
int main(void)
{
node *head = NULL;
node *ptr;
int n, i;
printf("How many numbers\n");
if (scanf("%d", &n) != 1)
{
fprintf(stderr, "Error while enterning list size\n");
return (EXIT_FAILURE);
}
for (i = 0; i < n; i++)
{
if (add_to_link_list(&head))
{
fprintf(stderr, "add_to_link_list failed\n");
return (EXIT_FAILURE);
}
}
ptr = head;
while (ptr != NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}
return (EXIT_SUCCESS);
}
it is giving me correct output but i am little suspicious in the
following two statements -
scanf("%d", &ptr->data) and printf("%d\n", ptr->data).
/********** LINK LIST **********/
#include <stdio.h>
#include <stdlib.h>
typedef struct node_s
{
void *data;
struct node_s *next;
}node;
int add_to_link_list(node **head)
{
node *ptr;
int temp;
ptr = malloc(sizeof(node));
if (ptr == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}
ptr->data = malloc(sizeof(int));
if (ptr->data == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}
printf("Enter data\n");
if (scanf("%d", &ptr->data) != 1)
{
fprintf(stderr, "Error while entering data\n");
return (1);
}
ptr->next = *head;
*head = ptr;
return (0);
}
int main(void)
{
node *head = NULL;
node *ptr;
int n, i;
printf("How many numbers\n");
if (scanf("%d", &n) != 1)
{
fprintf(stderr, "Error while enterning list size\n");
return (EXIT_FAILURE);
}
for (i = 0; i < n; i++)
{
if (add_to_link_list(&head))
{
fprintf(stderr, "add_to_link_list failed\n");
return (EXIT_FAILURE);
}
}
ptr = head;
while (ptr != NULL)
{
printf("%d\n", ptr->data);
ptr = ptr->next;
}
return (EXIT_SUCCESS);
}