动态内存分配两个结构,结构A具有指向结构B

时间:2019-06-16 09:36:35

标签: c

我有两个结构A和B。结构B在其中具有类型A的指针。 这两个结构/实例都应在运行时分配内存。是线性相关的。我发布的代码应该表达我的想法,但是行不通。请告诉我正确的方法。

#include <stdio.h>
#include <string.h>
#include <stdlib.h> //EXIT_SUCCESS, calloc

struct A
{
 char *name;
 int id;
};

struct B
{
 char *buildingName;
 struct a *ptra;
};


int main()
{

   int employe = 1;
   int NrOfBuildinTemplates = 3;

   struct A *humans;
   struct B *buildings; 

   humans =  calloc(employe, sizeof(struct A));
   buildings = calloc(NrOfBuildinTemplates, sizeof(struct B));

   buildings[0].buildingName = strdup("Building A");
   buildings[1].buildingName = strdup("Building B");
   buildings[2].buildingName = strdup("Building C");


   int count = 100, n = 0;
   for (size_t i = 3; i < count; i++)
   {
      buildings = realloc (buildings, sizeof(struct B) * (i+1));
      buildings[i].buildingName = strdup("Building XYZ");
      buildings[i].ptra = &(humans[n]);
      buildings[i].ptra->name = strdup("NameXYZ"); 
      humans = realloc(humans, sizeof(struct A) * (n+1));
      n++;
   }


   for (size_t i = 3; i < count; i++)
   {
      printf("%s -> %s\n", buildings[i].buildingName, buildings[i].ptra->name);
      n++;
   }
 return 0;
}

1 个答案:

答案 0 :(得分:0)

  buildings = realloc(buildings, i+1);

这是错误的。应该是:

  buildings = realloc(buildings, sizeof(struct B) * (i+1));

这有一个类似的问题:

  humans = realloc(humans, n+1);

此外,此代码完全令人困惑。我不建议如何解决它,因为我不知道您认为它会做什么:

  buildings[i].ptra = (*buildings->ptra) calloc(1, buildings->ptra);
  buildings[i].ptra = &(humans[n]);
  buildings[i].ptra = strdup("NameXYZ");