For the struct
typedef struct sharedData
{
sem_t *forks;
}sharedData;
I get a warning when I try to do this:
sharedData sd;
sem_t forks[5];
sd.forks = &forks; // Warning: assignment from incompatible pointer type
Am I misunderstanding or missing something?
The problem is that &forks
has type
sem_t (*)[5]
That is, a pointer to an array of five sem_t
s. The compiler warning is because sd.forks
has type sem_t*
, and the two pointer types aren't convertible to one another.
To fix this, just change the assignment to
sd.forks = forks;
Because of C's pointer/array interchangeability, this code will work as intended. It's because forks
will be treated as &forks[0]
, which does have type sem_t *
.
The above is a great explanation of but remember that
sd.forks = forks;
is the same as....
sd.forks = &forks[0];
I like the second one for clarity. If you wanted the pointer to point to the third element...
sd.forks = &forks[2];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With