Warning about assignment from incompatible pointer type when using pointers and arrays?
11,367
Solution 1
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 *
.
Solution 2
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];
Author by
PPP
Updated on June 10, 2022Comments
-
PPP almost 2 years
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?