【问题标题】:create thread incompatible type [duplicate]创建线程不兼容类型[重复]
【发布时间】:2015-08-15 08:28:59
【问题描述】:

您好,我正在尝试创建一个线程来调用一个采用结构的函数。 我面临的问题是 gcc 告诉我一个不兼容的指针

这是错误

warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [enabled by default]
/usr/include/pthread.h:225:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(struct sonicPins *)

与此错误相关的代码行 pthread_create(&thr1, NULL, &threadFunc,(void*) &args1);

这是它试图调用的函数

void* threadFunc(struct sonicPins *args)

结构体在sonicThread.h中定义,主要指向结构体

在我的主要功能之上

struct sonicPins *args1;

我主要有

args1 = malloc(sizeof(struct sonicPins));

args1->trig1 = 21;
args1->echo1 = 20;
//front right.
args1->trig2 = 16;
args1->echo2 = 12;
//rear left;
args1->trig3 = 26;
args1->echo3 = 19;
//rear right.
args1->trig4 = 13;
args1->echo4 = 6;

我尝试了各种方法来解决该问题,但找不到或想出解决问题的方法。

【问题讨论】:

  • 我回滚了您的编辑,因为它使下面的答案毫无意义。得到答案后请不要更改代码。发布新问题或添加更新代码而不删除旧代码。

标签: c struct pthreads


【解决方案1】:

GCC 的错误信息很简单:pthread_create 方法需要一个接受 void* 参数的方法。

把你的函数改成这样:

void* threadFunc(void* sonicPinsPtr) {
    struct sonicPins* args = sonicPinsPtr;

    // rest of your code here
}

【讨论】:

  • 我确实有它,但发现我无法访问该结构。在被调用的函数内部,我有 echo = args->echo1; Thiis 返回以下错误: sonicThread.c: In function 'threadFunc': sonicThread.c:11:8: error: 'echo' undeclared (first use in this function) sonicThread.c:11:8: note: each undeclared identifier对于它出现在 sonicThread.c:11:19 中的每个函数只报告一次:警告:取消引用 'void *' 指针 [默认启用] sonicThread.c:11:19:错误:请求成员 'echo1' 不是结构或联合
  • @JamesSmith 那么您应该显示更多代码,因为这是您最初问题的 正确 答案——再看一下此答案中的代码,当然您需要指向您的 struct 类型的指针首先...
  • @JamesSmith:然后在线程函数内部执行:struct sonicPins * p = sonicPinsPtr; 并使用p 访问struct sonicPins 的成员,就像这样p->echo1
  • 在 C 中不需要强制转换 void 指针(这里:指向struct sonicPins *),也不建议这样做。
  • "alk" 是正确的,这是一个c 问题,所以请删除多余的和分散注意力的(在特殊情况下甚至是危险的)演员表。它应该只是阅读struct sonicPins *args = sonicPinsPtr;。 @JamesSmith 确保你的 struct sonicPins 在你的函数使用它时被声明(所以将它移到你的 threadFunc 的定义之上或做一个前向声明。)
猜你喜欢
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
相关资源
最近更新 更多