2014-12-04 414 views
1

我试图编译我的代码时不断收到错误。错误如下: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),这不断抛出我送行。有任何想法吗?

+0

第一个答案解释了如何解决您的问题。 – 2501 2014-12-04 03:10:57

回答

4

它抱怨线程函数(绑定到的pthread_create第三个参数),你可以修改采取void *参数,然后用它做任何事情之前将它转换回:

void *start (void *voidData) { 
    threadData *data = voidData; 
    // rest of code here, using correctly typed data. 

可能也选择将数据指针(第四个参数)强制到预期的类型:

(void*)(&(data[id])) 

,但我不认为这是必要的,因为一个void *为s无法自由兑换大多数其他指针。


你可以看到这个问题在这个小而完整的程序:

#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); 
} 

这编译没有警告,并运行良好。

+0

@paxidiablo好吧,我试过那个确切的东西,它仍然给第三个参数上的错误,开始。 – jgabb 2014-12-04 03:26:09

+0

@jgabb,那么你需要添加更多信息的问题。使用'void * start(void *)'使它成为_exact_的正确类型,所以我认为你在某个地方犯了一个错字,或者你仍然在原型或其他东西中使用旧的声明。如果错误消息是相同的,那么你没有改变代码(因为它仍然提到'threadData *')。 – paxdiablo 2014-12-04 03:31:20

+0

你是对的=)谢谢! – jgabb 2014-12-04 04:38:11

相关问题