简体   繁体   English

Typedef结构无法转换为指针

[英]Typedef struct cannot be cast to pointer

I've seen this question in multiple posts but I have yet to find one that has a good explanation for me. 我已经在多个帖子中看到了这个问题,但是我还没有找到一个对我有很好解释的问题。 Im trying to create a linked list but the struct nor the functions cant be called without getting the error cannot cast to a pointer. 我试图创建一个链表,但是在没有得到错误的情况下不能调用结构或函数,不能将其转换为指针。 Its really bugging me. 它真的困扰我。 Any help would be appreciated on how to get this working right. 任何帮助将不胜感激如何使其正常工作。 Heres some of the code below thats the issue. 这是多数民众赞成在下面的一些代码。

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

node *head = NULL;

node* create(void *data, node *next)
{
    node *new_node = (node*)malloc(sizeof(node));
    if(new_node == NULL)
    {
        exit(0);
    }else{

        new_node->data = data;
        new_node->next = next;
        return new_node;
    }

}

node* prepend(node *head, void *data)
{
    node *new_node = create(data,head);
    head = new_node;
    return head;
}


void preload_adz(int adz_fd)
{
    struct adz adz_info;
    char adz_data[40];
    char adz_text[38];
    int adz_delay;
    char adz_delayS[2];

    read(adz_fd,adz_data,40);
    strncpy(adz_text,adz_data + 2,40-2);
    sprintf(adz_delayS, "%c%c",adz_data[0],adz_data[1]);
    adz_delay = atoi(adz_delayS);

    adz_info.delay = adz_delay;
    strncpy(adz_info.text,adz_text,38);

    head = prepend(head, (void*)adz_info); //<---This line throws the error

    while(read(adz_fd,adz_data,40) > 0)
    {

    }
}
struct adz adz_info;

...

head = prepend(head, (void*)adz_info); //<---This line throws the error

The problem here is adz_info is not a pointer, it's the actual struct on the stack. 这里的问题是adz_info不是指针,而是堆栈上的实际结构。 Passing adz_info into a function will copy the struct. adz_info传递给函数将复制该结构。

You need a pointer to that struct. 您需要一个指向该结构的指针。 Use & to get its address. 使用&获取其地址。 Once you have the pointer, you don't need to cast it to void pointer, that cast is automatic. 一旦有了指针,就不需要将其强制转换为void指针,该转换是自动的。

head = prepend(head, &adz_info);

Note that casting is a bookkeeping thing. 请注意,铸造是记账的事情。 Casting to void * doesn't turn a struct into a pointer, it says "compiler, ignore the declared type of this variable and just trust me that this is a void pointer". 强制转换为void *不会将结构转换为指针,它表示“编译器,忽略此变量的声明类型,只相信我这是一个void指针”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM