Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 431
randomThought Avatar asked Feb 04 '11 06:02

randomThought


2 Answers

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 *.

like image 190
templatetypedef Avatar answered Sep 17 '22 17:09

templatetypedef


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];
like image 24
newrev426 Avatar answered Sep 19 '22 17:09

newrev426