C语言 如何在 memcpy 之前对结构数组进行 malloc



我认为在没有错误检查的情况下做memcpy是可以的。但是,我不确定我们应该如何更正下面的代码,即。我们如何对结构数组进行"检查"?

以下是结构体的定义:

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[];

在主()

   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 %sn", 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 %sn", check[1].suit.inner.option);
   free(check);

这个:

memcpy(&check, &structArrayToBeCheck, sizeof(structArrayToBeCheck));

无效,因为您要将结构数组复制到指针数组中。

请记住,动态分配的结构集不是连续的。指针数组是连续的,但它们指向单独分配的内容。

尝试:

for (i = 0; i != n ; i++) {
    check[i] = malloc(sizeof(struct contain));
    memcpy( check[i], ArrayToBeCheck[i], sizeof(ArrayToBeCheck[i]));
}

此外,如果结构副本始终作为块分配/解除分配(如您的示例所示),则无需单独分配它们。 只需为整个阵列分配足够的空间:

struct contain *check = malloc(n*sizeof(struct contain));
memcpy( check, structArrayToBeCheck, sizeof(structArrayToBeCheck));
// do things with check[0], check[1], ... check[n-1]
free(check);
struct contain **check = malloc(n*sizeof(struct contain *));
for (int i = 0; i != n ; i++) {
    check[i] = malloc(sizeof(struct contain));
} 

这可能是安全的分配方式。这里您想要的n是您想要的数组大小。

然后

// Do not forget to free the memory when you are done:
for (int i = 0; i != n ; i++) {
    free(check[i]);
}
free(check);

相关内容

  • 没有找到相关文章