指针类型不兼容的赋值

6
我已经设置了以下结构体:

struct:

typedef struct _thread_node_t {
    pthread_t thread;
    struct thread_node_t *next;
} thread_node_t;

...然后我定义了:

// create thread to for incoming connection
thread_node_t *thread_node = (thread_node_t*) malloc(sizeof(thread_node_t));
pthread_create(&(thread_node->thread), NULL, client_thread, &csFD);

thread_node->next = thread_arr; // assignment from incompatible pointer type

thread_arr = thread_node;

其中 thread_arr 是 thread_node_t *thread_arr = NULL;

我不明白为什么编译器在抱怨。也许我理解错了什么。

2个回答

5

“struct thread_node_t *next;” 应该改为 “struct _thread_node_t *next;”


同时,不需要进行 显式 强制类型转换。

thread_node_t *thread_node = (thread_node_t*) malloc(sizeof(thread_node_t));

to

thread_node_t *thread_node = malloc(sizeof(thread_node_t));

哦,天啊!是啊...谢谢。我简直不敢相信我错过了那个。我之前的一个程序中有一个这样的结构体在工作,我一直在苦苦寻找解决方法。非常感谢。 - Hristo
关于显式转换:ANSI C 不需要,但在 C++ 中是必需的。 - Macmade
或者说,thread_node_t *thread_node = malloc(sizeof *thread_node); - Steve Jessop
1
@Macmade:我还没有完全决定是否要对malloc的结果进行强制转换,但是其中一个影响因素是,正如你所说,如果省略强制转换,它将无法编译为C ++。我认为这是不强制转换的一个很好的理由! - Steve Jessop

3

这是因为thread_arr是一个thread_node_t指针,而你的next成员是一个struct thread_node_t指针,两者不同。


我试图弄清楚的是,struct thread_node_t 是什么?为什么提问者的 typedef 能够编译通过? - Steve Jessop
1
哦,我明白了,这是一个不完全类型的前向声明。 - Steve Jessop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接