【问题标题】:Passing struct into a function from pthread_create将结构从 pthread_create 传递给函数
【发布时间】:2013-11-09 03:15:43
【问题描述】:

我是 C 的新手,谁能帮帮我?

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <windows.h>

struct New
{
 char a;
 int b;
};


void *Print_Func (void* Ptr)
{
 Sleep(5);
 printf("%d\n",Ptr.a);
 printf("%d\n",Ptr.b);
}

int main (void)
{
 pthread_t Thread1;
 while(1)
 {
  struct New Flag;
  Flag.a=5;
  Flag.b=1234567;
  pthread_create(&Thread1,NULL,Print_Func,&Flag);
  pthread_join(Thread1,NULL);
  printf("\n");
 }
 system("pause>nul");
}

为什么编译器总是报告

错误:在非结构或联合中请求成员“a”

错误:在不是结构或联合的东西中请求成员“b”

环境。 : Windows7 C:B mingw32-gcc.exe

谢谢

【问题讨论】:

  • 欢迎来到 Stack Overflow。请尽快阅读About 页面。请注意,您只能将相同的变量 Flag 传递给 pthread_create(),因为您不会更改线程之间的值并且线程不会修改它。很多时候,您需要为每个线程传递一个单独的值,因为每个线程要执行的任务略有不同,而参数会告诉它不同之处。

标签: c pthreads


【解决方案1】:

请报告您粘贴到问题中的确切代码发生错误的行号。

问题出现在这里:

void *Print_Func (void* Ptr)
{
 Sleep(5);
 printf("%d\n",Ptr.a);
 printf("%d\n",Ptr.b);
}

void * 不是结构。您需要将void * 转换为struct New *

void *Print_Func (void *Ptr)
{
    struct New *data = Ptr;
    Sleep(5);
    printf("%d\n", data->a);
    printf("%d\n", data->b);
}

缩进一个以上的空格也是值得的(在 SO 上首选 4 个),而且逗号后面有空格通常看起来更好。

【讨论】:

  • 太好了,非常感谢 :-)
猜你喜欢
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 2020-09-26
  • 2023-03-31
  • 2015-12-24
  • 2011-07-21
  • 1970-01-01
  • 2012-05-09
相关资源
最近更新 更多