【发布时间】:2014-03-10 07:07:35
【问题描述】:
我认为在没有 malloc'ing 检查的情况下进行 memcpy 是可以的。但是,我不确定我们将如何更正下面的代码,即。我们如何 malloc struct array 'check'?
结构体的定义如下:
struct contain {
char* a; //
int allowed; //
struct suit {
struct t {
char* option;
int count;
} t;
struct inner {
char* option;
int count;
} inner;
} suit;
};
我们用一些值初始化它:
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[];
在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);
[由 Michael Burr 和 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);
【问题讨论】:
-
"结构包含检查[];"你能使用这样的语法吗?这里的 sizeof(check) 是多少?