5

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?

2 Answers 2

12

The problem is that &forks has type

sem_t (*)[5]

That is, a pointer to an array of five sem_ts. 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 *.

Sign up to request clarification or add additional context in comments.

Comments

1

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.