C 不定结构数组的动态分配

C 不定结构数组的动态分配,c,dynamic,C,Dynamic,我知道我可以通过以下方式动态分配一个包含10个结构的数组: #include <stdio.h> #include <stdlib.h> struct studente{ long matricola; int esami; }; int main(){ struct studente *V; int i; V=malloc(10*sizeof(struct studente)); return 0; } 但是如果向量中包含的结构的数量没有定义?也就是说,如果用

我知道我可以通过以下方式动态分配一个包含10个结构的数组:

#include <stdio.h>
#include <stdlib.h>
struct studente{
long matricola;
int esami;
};
int main(){
 struct studente *V;
 int i;
 V=malloc(10*sizeof(struct studente));
 return 0;
}

但是如果向量中包含的结构的数量没有定义?也就是说,如果用于填充结构的数据系列包含在外部文件中,并且结构的数量与其中包含的数据集的数量相对应?

可能您的代码经过修改但未完成的扩展会根据需要增加分配给V的内存:

#include <stdio.h>
#include <stdlib.h>

struct student
   {
   long matricola;
   int esami;
   };

int main()
   {
   int rCode=0;
   struct studente *V= NULL;
   int V_elements = 0;
   int V_elementsUsed = 0;
   ...

   V=malloc(10*sizeof(struct studente));
   if(NULL == V)
      {
      fprintf(stderr, "malloc() failed.\n");
      rCode=ENOMEM;
      goto CLEANUP;
      }
    V_elements=10;

   ...

   while(/*Read structure from file succeeds */)
      {
      if(V_elementsUsed == V_elements)
         {
         struct studente *tmp = realloc(V, (V_elements + 10) * sizeof(struct studente));
         if(NULL == tmp)
            {
            fprintf(stderr, "realloc() failed.\n");
            rCode=ENOMEM;
            goto CLEANUP;
            }

         V=tmp;
         V_elements += 10; 
         }

      V[V_elementsUsed]./*field*/ = /*from file*/;
      ++V_elementsUsed;
      }        

...

CLEANUP:

   if(V)
      free(V);

   return(rCode);
   }

见realloc。猜猜尺寸;malloc,然后realloc。你可以1提前确定学生人数,2使用链表,3使用realloc,它允许你在需要时增加缓冲区的大小。链表是什么?‎仅仅发布代码并没有多大帮助。考虑添加解释。在这种情况下,只需要一个代码示例就可以用最少的代码片段进行解释。