从double转换为指针

Mik*_* B. 2 c linked-list generic-list

我用C相当的新手,现在我想实现3种元素的基本通用的链表,每个元素都将包含不同的数据类型值- int,chardouble.

这是我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我对前两个元素没有问题,但是当我尝试将double类型的值赋给第三个元素时,我得到一个错误:« 无法转换doubledouble * ».

这个错误的原因是什么?为什么我不能得到相同的错误intchar?而最重要的问题是:如何解决这个问题,如何为double第三个元素的数据字段赋值?

问题字符串是« (double*)third->data = 5.6;».

谢谢.

Mar*_*eed 6

在你的"工作"示例中,你正在调用malloc获取指向一些新分配空间的指针,然后立即抛出指针并用整数或字符值替换指针值.这或多或少是偶然的,因为在大多数C实现中,指针单元格可以包含整数或char值,但是您应该收到警告.如果您在这些分配后实际尝试取消引用数据指针,则可能会发生崩溃和核心转储.

你想放的值在地方指出,通过指针,而不是指针本身.这意味着你需要一个额外的*:

 *((double *)third->data) = 5.6;
Run Code Online (Sandbox Code Playgroud)

*(double *)类型转换的类型是名称的一部分- "指针翻一番".演员说"把它的价值third->data看作是指向双重的指针".结果仍然是一个指针,所以当你指定它时,你正在改变指针指向的位置(并且可能使它指向某个地方毫无意义).相反,您希望为已经指向的位置指定一个值,这就是外部*所做的.

但是,如果您只存储像int,char和等基本类型,double则不需要通过指针(并担心伴随的内存管理).你可以使用一个联盟:

struct node 
{
    struct node *next;
    union {
        char c;
        int  i;
        double d;
    } data;
 }
Run Code Online (Sandbox Code Playgroud)

然后你会做例如

head->data.i = 2;
second->data.c = 'b';
third->data.d = 5.6;
Run Code Online (Sandbox Code Playgroud)