简体   繁体   English

两个struct的动态内存分配,struct A有一个指向struct B的指针

[英]Dynamic memory allocation of two structs, struct A has a pointer to struct B

I have two structs A and B. Struct B has pointer in it of the type struct A. Both structs/instances should allocate memory on runtime.我有两个结构 A 和 B。结构 B 中有结构 A 类型的指针。两个结构/实例都应该在运行时分配内存。 The are linear dependent.是线性相关的。 I posted code which should present my idea, which doesn´t work.我发布了应该展示我的想法的代码,但它不起作用。 Please show me the right way.请告诉我正确的方法。

#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;
}
  buildings = realloc(buildings, i+1);

This is wrong.这是错误的。 It should be:它应该是:

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

There's a similar issue with this:这有一个类似的问题:

  humans = realloc(humans, n+1);

Also, this code is completely baffling.此外,这段代码完全令人费解。 I can't suggest how to fix it because I have no idea what you think it does:我不能建议如何修复它,因为我不知道你认为它做了什么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM