void pointers and scanf/printf

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • pereges

    void pointers and scanf/printf

    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_lis t(node **head)
    {
    node *ptr;

    ptr = malloc(sizeof(n ode));
    if (ptr == NULL)
    {
    fprintf(stderr, "Memory allocation failed\n");
    return (1);
    }

    ptr->data = malloc(sizeof(i nt));
    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_li st(&head))
    {
    fprintf(stderr, "add_to_link_li st failed\n");
    return (EXIT_FAILURE);
    }
    }

    ptr = head;

    while (ptr != NULL)
    {
    temp = (int *)ptr->data;
    printf("%d\n",* temp);
    ptr = ptr->next;
    }

    return (EXIT_SUCCESS);
    }
  • rahul

    #2
    Re: void pointers and scanf/printf

    On Mon, 21 Jul 2008 02:52:31 +0530, pereges <Broli00@gmail. comwrote:

    typedef struct node_s
    {
    void *data;
    struct node_s *next;
    >
    }node;
    If you want int then you should have:

    typedef struct node_ {
    int data;
    struct node_ *next;
    } node;

    If you want your list to be hetrogenous, you can have a union:

    typedef struct node_ {
    union {
    char cData;
    int iData;
    float fData;
    };
    struct node_ *next;
    } node;

    There was a discussion about anonymous unions invoking undefined
    behaviour. So, to avoid that:

    typedef struct node_ {
    union {
    char c;
    int i;
    float f;
    }data;
    struct node_ *next;
    } node;

    --
    Nothing worth having comes easy.

    -- Posted on news://freenews.netfront.net - Complaints to news@netfront.n et --

    Comment

    Working...