I have two structures as shown below
struct server{
// some members
};
struct msg{
struct server* servers;
};
Then I do this.
struct msg msg1;
struct server s1,s2;
msg1.servers = (struct server *)malloc(2*sizeof(struct server));
msg1.servers[0] = &s1; // compilation error
msg1.servers[1] = &s2; // compilation error
This code does not compile and giving the following error : incompatible types when assigning to type ‘struct server’ from type ‘struct server *’.
What am I doing wrong?
The problem here is that the expression
msg1.servers[0]producets astruct serverbut you’re providing astruct server*(a pointer type vs a non-pointer type). There are two ways to fix thisThe first is to simply provide the
struct serverinstances by value as the code expectsThis will work if
struct serveris a type that behaves properly when copied around.The second is necessary if you want to continue using
struct server*in thestruct msg. In this case you need a double pointer to store the server pointers. And you need to adjust yourmallocstatement appropriately