C 警告 : incompatible pointer types passing

标签 c pointers parameters pthreads incompatibletypeerror

这个问题在这里已经有了答案:





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/

相关文章:

c - 编写一个排序函数对指向结构的指针数组进行排序

c - .lib 中的函数已定义,但当我从同一个 .lib 生成 .so 时,该函数不存在

c - 从 C 中的二进制文件中获取 32 位指令

c - 我的代码中某个测试用例的奇怪行为

c++ - 如何从另一个指针指向的内存地址获取数据?

r - 在 R 中的第二个函数中使用一个函数中的变量值

c - 如何在 if 语句中的条件下创建宏

字符串的 C++ vector 、指向函数的指针以及由此产生的挫败感

reporting-services - SSRS根据多值参数对多个表进行分组

parameters - 如何先验选择决策树算法的参数?