#include <stdlib.h>
#include <stdio.h>
struct foo{
int id;
char *bar;
char *baz[6];
};
int main(int argc, char **argv){
struct foo f;
f.id=1;
char *qux[6];
f.bar=argv[0];
f.baz=qux; // Marked line
return 1;
}
This is just some test code so ignore that qux doesn’t actually have anything useful in it.
I’m getting an error on the marked line, incompatible types when assigning to type ‘char *[6]’ from type ‘char **’ but both of the variables are defined as char *[6] in the code. Any insight?
The problem with this code is that the line
Tries to assign the array
quxto the arraybaz. In C, arrays are not variables and cannot be assigned new values. To see a simpler example, this code:Is illegal because the second line tries to assign the second array the value of the first, which is not allowed in C.
To fix this, you’ll probably want to write an explicit loop to copy the elements over, as seen here:
This is legal because each individual element of the array is a
char *, which can be assigned.You sometimes also see
memcpyused to assign arrays:This copies over the raw bytes of all the fields in the arrays.