简体   繁体   English

如何在不知道大小的情况下分配结构数组

[英]How to malloc array of structs without knowing size

I have a struct of words: 我有一个字词结构:

typedef struct {
   char *word;
   unsigned long occurrences;
} Word;

and I want to malloc an array of these but I don't know how large the size will be. 我想分配这些的数组,但我不知道大小会多大。 Is there a way to malloc an array of structs without knowing the size of the array beforehand? 有没有一种方法可以在不事先知道数组大小的情况下分配结构数组?

Thanks. 谢谢。

You can allocate memory with malloc() , and then change size with realloc() 您可以使用malloc()分配内存,然后使用realloc()更改大小

typedef struct {
 char *word;
 unsigned long occurrences;
} Word;

int main()
{
  Word *arr = malloc(sizeof(Word) * n);
  // do smth
  // need more
  arr = realloc(arr, sizeof(Word) * more);

  return 0;
}

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

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