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:
-
What is the reason for this error?
-
Why don’t I get the same error in case of
intorchar? -
How to assign a
doublevalue to the data field of the third element?
The problem string is (double*)third->data = 5.6;.
You are casting the pointer, but you need to derefernce it for the assignment, the assignment worked for the first two since the
intandcharwere casted to pointers, it should be:Anyway, there should be warning for such a cast in first place.