Warning about assignment from an incompatible pointer type when using pointers and arrays?

For 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 

Did I misunderstand or miss something?

+4
source share
2 answers

The problem is that &forks is of type

 sem_t (*)[5] 

That is, a pointer to an array of five sem_t s. A compiler warning is that sd.forks is of type sem_t* , and the two types of pointers are not converted to each other.

To fix this, just change the assignment to

 sd.forks = forks; 

Due to the interchangeability of the C pointer / array, this code will work as intended. This is because forks will be treated as &forks[0] , which has type sem_t * .

+11
source

The above explanation, but remember that

 sd.forks = forks; 

same as ....

 sd.forks = &forks[0]; 

I like the second for clarity. If you want the pointer to point to the third element ...

 sd.forks = &forks[2]; 
+1
source

Source: https://habr.com/ru/post/1338378/


All Articles