I think it is ok to do memcpy without malloc'ing check. However, I am unsure how shall we correct the code below, ie. How do we malloc struct array 'check'?
Here is the definition of the struct:
struct contain {
char* a; //
int allowed; //
struct suit {
struct t {
char* option;
int count;
} t;
struct inner {
char* option;
int count;
} inner;
} suit;
};
We initialized it with some values:
struct contain structArrayToBeCheck[] = {
{
.a = "John",
.allowed = 1,
.suit = {
.t = {
.option = "ON",
.count = 7
},
.inner = {
.option = "OFF",
.count = 7
}
}
},
{
.a = "John",
.allowed = 1,
.suit = {
.t = {
.option = "ON",
.count = 7
},
.inner = {
.option = "OK",
.count = 7
}
}
},
{
.a = "John",
.allowed = 1,
.suit = {
.t = {
.option = "ON",
.count = 7
},
.inner = {
.option = "OFF",
.count = 7
}
}
},
};
struct contain check[];
in main()
int i;
int n = sizeof(structArrayToBeCheck)/sizeof(struct contain);
printf( "There are %d elements in the array.\n", n);
struct contain **check = malloc(n*sizeof(struct contain *));
for (i = 0; i != n ; i++) {
check[i] = malloc(sizeof(struct contain));
}
memcpy(&check, &structArrayToBeCheck, sizeof(structArrayToBeCheck));
//printf( "check is %s\n", check[1]->suit.inner.option);
[Solved by Michael Burr and JKB]
int i;
int n = sizeof(structArrayToBeCheck)/sizeof(struct contain);
printf( "There are %d elements in the array.\n", n);
struct contain *check = malloc(n*sizeof(struct contain));
memcpy( check, structArrayToBeCheck, sizeof(structArrayToBeCheck));
// do things with check[0], check[1], ... check[n-1]
printf( "check is %s\n", check[1].suit.inner.option);
free(check);