void pointers and scanf/printf

Discussion in 'C Programming' started by pereges, Jul 20, 2008.

  1. pereges

    pereges Guest

    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);
    }
     
    pereges, Jul 20, 2008
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Goddard

    void pointers & void function pointers

    Peter Goddard, May 16, 2005, in forum: C Programming
    Replies:
    3
    Views:
    533
    Peter Goddard
    May 16, 2005
  2. whatluo

    (void) printf vs printf

    whatluo, May 26, 2005, in forum: C Programming
    Replies:
    29
    Views:
    1,328
  3. Replies:
    5
    Views:
    882
    S.Tobias
    Jul 22, 2005
  4. Replies:
    1
    Views:
    435
    Victor Bazarov
    May 23, 2007
  5. pereges

    void pointers and scanf/printf

    pereges, Jul 20, 2008, in forum: C Programming
    Replies:
    14
    Views:
    1,083
    Keith Thompson
    Jul 21, 2008
Loading...

Share This Page