C警告:不兼容的指针类型传递 [英] C warning: incompatible pointer types passing

查看:1816
本文介绍了C警告:不兼容的指针类型传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图编译我的code时,得到一个错误。误差如下:

I keep getting an error when trying to compile my code. The error is as follows :

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 *的开始(threadData *数据),而这种不断抛出我送行。有任何想法吗?

I'm trying to pass a struct to the function, void * start(threadData* data), and this keeps throwing me off. Any ideas?

推荐答案

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

It's complaining about the thread function (bound to the third parameter of pthread_create), you can modify that to take a void * argument and then cast it back before doing anything with it:

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

您的可能的还可以选择要挟数据指针(第四个参数),以预期的类型:

You may also opt to coerce the data pointer (fourth parameter) to the expected type:

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

但我不认为这是必要的,因为一个无效* 应该是自由兑换,并从其他大多数的指针。

but I don't think that's necessary since a void * is supposed to be freely convertible to and from most other pointers.

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

You can see the problem in this small yet complete program:

#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 *)'

记住,这只是一个的警告的不是错误,但如果你希望你的code干净编译,这是值得除暴安良。在制作这个答案(巴数据参数铸造)的顶部提到的更改为您提供了以下线程函数:

Keep in mind that it's just a warning, not an error but, if you want your code to compile cleanly, it's worth getting rid of. Making the changes mentioned at the top of this answer (bar the data parameter casting) gives you the following thread function:

void *start (void *voidData) {
        struct sData *data = voidData;
        printf ("[%s]\n", data->text);
}

这编译没有警告,并且运行得很好。

This compiles without warnings, and runs just fine.

这篇关于C警告:不兼容的指针类型传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆