Code:
#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);
}
printf("Enter data\n");
if (scanf("%d", &temp) != 1)
{
fprintf(stderr, "Error while entering data\n");
return (1);
}
ptr->data = malloc(sizeof(int));
if (ptr->data == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
return (1);
}
(int) ptr->data = temp;
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);
}
btw i didn't understand how the statement
printf("%d\n", ptr->data) was acceptable. The compiler did not warn me to do a typecast or anything. Can I get away witht his while using scanf as well ? scanf("%d", &ptr->data) ?