C警告:不兼容的指针类型传递
我在尝试编译代码时遇到错误。 错误如下:
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)
,这一直让我失望。 有任何想法吗?
它抱怨线程函数(绑定到pthread_create
的第三个参数),您可以修改它以获取void *
参数,然后在对它执行任何操作之前将其强制转换:
void *start (void *voidData) { threadData *data = voidData; // rest of code here, using correctly typed data.
您也可以选择将数据指针(第四个参数)强制转换为预期的类型:
(void*)(&(data[id]))
但我不认为这是必要的,因为void *
应该可以自由地转换为大多数其他指针。
您可以在这个小而完整的程序中看到问题:
#include #include #include 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 *)'
请记住,这只是一个警告,而不是错误,但是,如果您希望您的代码能够干净地编译,那么值得摆脱它。 进行此答案顶部提到的更改(bar数据参数转换)为您提供以下线程函数:
void *start (void *voidData) { struct sData *data = voidData; printf ("[%s]\n", data->text); }
这个编译没有警告,运行得很好。