user2967915
user2967915

Reputation: 69

Passing struct into a function from pthread_create

I am fairly a newbie in C, Could anyone help me ?

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

Why compiler always reports

error: request for member 'a' in something not a structure or union

error: request for member 'b' in something not a structure or union

Envir. : Windows7 C:B mingw32-gcc.exe

Thanks

Upvotes: 0

Views: 4409

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753555

Please report the line numbers where the errors occur for the exact code you paste into the question.

The problem occurs here:

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

A void * isn't a structure. You need to convert the void * into a struct New *:

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

It is also worth indenting by more than one space (4 is preferred on SO), and it generally looks better to have spaces after commas.

Upvotes: 2

Related Questions