Search code examples
clinked-listgeneric-list

Conversion from double to pointer


I'm quite newbie in C and now I'm trying to implement basic generic linked list with 3 elements, each element will contain a different datatype value — int, char and double.

Here is my code:

#include <stdio.h>
#include <stdlib.h>

struct node
{
    void* data;
    struct node* next;
};

struct node* BuildOneTwoThree()
{
    struct node* head   = NULL;
    struct node* second = NULL;
    struct node* third  = NULL;

    head    = (struct node*)malloc(sizeof(struct node));
    second  = (struct node*)malloc(sizeof(struct node));
    third   = (struct node*)malloc(sizeof(struct node));

    head->data = (int*)malloc(sizeof(int));
    (int*)(head->data) = 2;
    head->next = second;

    second->data = (char*)malloc(sizeof(char));
    (char*)second->data = 'b';
    second->next = third;

    third->data = (double*)malloc(sizeof(double));
    (double*)third->data = 5.6;
    third->next = NULL;

    return head;
}

int main(void)
{
    struct node* lst = BuildOneTwoThree();

    printf("%d\n", lst->data);
    printf("%c\n", lst->next->data);
    printf("%.2f\n", lst->next->next->data);

    return 0;
}

I have no problem with the first two elements, but when I try to assign a value of type double to the third element I get an error:

can not convert from double to double *

My questions:

  1. What is the reason for this error?

  2. Why don't I get the same error in case of int or char?

  3. How to assign a double value to the data field of the third element?

The problem string is (double*)third->data = 5.6;.


Solution

  • You are casting the pointer, but you need to derefernce it for the assignment, the assignment worked for the first two since the int and char were casted to pointers, it should be:

    *((int*)(head->data)) = 2;
    *((char*)(second->data)) = 'b';
    *((double*)(third->data)) = 5.6;
    

    Anyway, there should be warning for such a cast in first place.