简体   繁体   中英

C void pointer casting

typedef struct{
    void *val;
}struct_t;

void test(int val)
{
    struct_t *s = malloc(sizeof(struct_t));

    s->val = malloc(sizeof(int));

   *(int*)&s->val = val;

    free(s->val);
}

The free generates a sigabrt but I think that's more just a symptom of the way that I'm casting s->val to get the assignment to work. What's the proper way to perform this assignment?

 *(int*)&s->val = val;

说“在结构s中获取字段val的地址,然后将其写入“ val”。这使s-> val指向测试“ val”的参数中存储的地址。您的意思是

*(int*)s->val = val;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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