2

I have an array of structs and I intend to pass each element of the array into separate pthreads in a for loop.

Here's my struct:

struct arrayData{
int *a;
int *b;
int up, low;
}

Here's the pointer to the first struct and a malloc (don't know if I quite get what goes on here):

struct arrayData * instance;
        instance = malloc(sizeof(struct arrayData)*n);

Here's my call to pthread_create:

pthread_create( &thread[i], NULL, add, (void *)instance[i]);

And for that line I'm getting the message "Cannot convert to a pointer type".

What could be wrong with that line?

Brian Howell
  • 67
  • 2
  • 13
Chucky
  • 1,701
  • 7
  • 28
  • 62

2 Answers2

8

You are trying to convert a struct to a pointer in the last parameter. You need to pass the the struct's address with &.

pthread_create( &thread[i], NULL, add, &instance[i]);

As jørgensen mentioned, the void * cast is unnecessary.

Community
  • 1
  • 1
Matt Eckert
  • 1,946
  • 14
  • 16
  • Excellent! Thank you. Need to hit the books on C this summer as I'm way too rusty. Why might I still be getting a warning for that line which says "Passing argument 3 of 'pthread-create' from incompatible pointer type."? – Chucky Mar 28 '12 at 19:11
  • What's the signature of your `add` function? – Matt Eckert Mar 28 '12 at 19:14
  • Excellent! Can you explain to me why this guy didn't have to do that in this tutorial: http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html – Chucky Mar 29 '12 at 08:10
  • @mteckert: this is not needed in C. In fact, using `&` for function pointers makes it impossible to do preprocessor-time substitutions (`#define add NULL` -- not that NULL is useful for pthread_create, but it is in other situations). – jørgensen Mar 29 '12 at 08:17
  • @Chucky where have you declared `add`? – Matt Eckert Mar 29 '12 at 14:08
2

instance is of type struct arrayData *, hence instance[i] is of type struct arrayData, which is an aggregate, not a pointer. Intended use was probably

pthread_create(&thread[i], NULL, add, &instance[i]);

The cast, btw, is pointless.

jørgensen
  • 10,149
  • 2
  • 20
  • 27