void pointers and scanf/printf

P

pereges

have i written this program correctly ?

i'm a bit suspicious about the statement :scanf("%d", ptr->data)



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

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;
int *temp;

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)
{
temp = (int *)ptr->data;
printf("%d\n",*temp);
ptr = ptr->next;
}

return (EXIT_SUCCESS);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top