我在C中很新手,現在我試圖用3個元素實現基本的通用鏈表,每個元素將包含不同的數據類型值 - int
,char
和double
。從雙指針轉換爲
這裏是我的代碼:
#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;
}
我與前兩個元素沒有問題,但是當我嘗試分配雙到第三元素類型的值,我得到一個錯誤:«不能從double
轉換爲double *
»。
這個錯誤的原因是什麼?爲什麼在int
或char
的情況下我不會得到相同的錯誤? 而最重要的問題是:如何解決這個問題,如何爲第三個元素的數據字段賦值double
?
問題字符串是«(double*)third->data = 5.6;
»。
謝謝。
我仍然說使用指針來存儲基元類型是愚蠢的。 –