这个问题在这里已经有了答案:
c pthread passing array of type int
(2 个回答)
6年前关闭。
尝试编译我的代码时,我不断收到错误消息。错误如下:
warning: incompatible pointer types passing
'void *(threadData *)' to parameter of type 'void * (*)(void *)'
[-Wincompatible-pointer-types]
pthread_create(&threads[id], NULL, start,&data[id]);
我正在尝试将结构传递给函数
void * start(threadData* data)
,这一直让我失望。有任何想法吗?
最佳答案
它提示线程函数(绑定(bind)到 pthread_create
的第三个参数),您可以将其修改为采用 void *
参数,然后在对其进行任何操作之前将其转换回:
void *start (void *voidData) {
threadData *data = voidData;
// rest of code here, using correctly typed data.
您还可以选择将数据指针(第四个参数)强制转换为预期类型:
(void*)(&(data[id]))
但我不认为这是必要的,因为
void *
应该可以自由转换为大多数其他指针。您可以在这个小而完整的程序中看到问题:
#include <stdio.h>
#include <string.h>
#include <pthread.h>
struct sData { char text[100]; };
void *start (struct sData *data) {
printf ("[%s]\n", data->text);
}
int main (void) {
struct sData sd;
pthread_t tid;
int rc;
strcpy (sd.text, "paxdiablo");
rc = pthread_create (&tid, NULL, start, &sd);
pthread_join (tid, NULL);
return 0;
}
编译时,您会看到:
prog.c: In function 'main':
prog.c:20:2: warning: passing argument 3 of 'pthread_create' from
incompatible pointer type [enabled by default]
In file included from prog.c:3:0:
/usr/include/pthread.h:225:12: note: expected
'void * (*)(void *)' but argument is of type
'void * (*)(struct sData *)'
请记住,这只是一个警告,而不是错误,但是,如果您希望您的代码能够干净地编译,那么值得摆脱它。进行此答案顶部提到的更改(禁止数据参数转换)为您提供以下线程函数:
void *start (void *voidData) {
struct sData *data = voidData;
printf ("[%s]\n", data->text);
}
这编译没有警告,并且运行得很好。
关于C 警告 : incompatible pointer types passing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27285565/