具有不同大小结构的结构数组的 malloc()
如果每个结构都包含一个大小不同的字符串数组,那么如何正确地 malloc 一个结构数组?
因此每个结构可能有不同的大小,并且不可能
realloc(numberOfStructs * sizeof(structName))
之后
malloc(initialSize * sizeof(structName)
如何为此分配内存并跟踪正在发生的情况?
How does one malloc an array of structs correctly if each struct contains an array of strings which vary in size?
So each struct might have a different size and would make it impossible to
realloc(numberOfStructs * sizeof(structName))
after
malloc(initialSize * sizeof(structName)
How does one allocate memory for this and keep track of what is going on?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你的结构体有一个 char *,它会占用一个指针的大小。如果它有一个char[200],它就占用两百个字节。
If your structure has a char *, it takes up the size of one pointer. If it has a char[200], it takes up two hundred bytes.
我根据您提供的信息在这里做出一些猜测。我认为想要
realloc
结构数组的唯一原因是如果您想向该数组添加更多结构。这很酷。有很多理由需要这种动态存储。处理它的最佳方法是保留指向这些结构的指针数组,特别是如果结构本身是动态的。例子:I am making some guesses here, based on the information you have provided. The only reason I can see for wanting to
realloc
an array of structs is if you want to add more structs to that array. That's cool. There are plenty of reasons to want that kind of dynamic storage. The best way to handle it, especially if the structures are themselves dynamic, is to keep an array of pointers to these structures. Example:一般来说,你不会。您可能想要这样做有两个原因:
free()
将释放整个内存块。但除非您遇到特殊情况,否则两者都不是非常引人注目,因为这种方法存在严重缺陷:
如果您这样做,那么
block[i]
就没有意义。您还没有分配数组。如果不检查结构或不了解有关块中结构的大小/位置的外部信息,就无法知道下一个结构从哪里开始。You don't, generally. There are two reasons you might want to do this:
free()
will release the entire block of memory.But unless you have an exceptional situation, neither are very compelling, because there is crippling drawback to this approach:
If you do this, then
block[i]
is meaningless. You have not allocated an array. There is no way to tell where your next struct starts without either examining the struct or having outside information about the size/position of your structs in the block.目前尚不清楚您的 struct 类型是如何声明的。 C99 对于此类事情有一个特殊的构造,称为
struct
的灵活数组成员:你可以做类似的事情
你可以分配这样一个野兽
并重新分配它
为了更舒适地使用它,你可能最好将其包装到宏或内联函数中。
It is not so clear how your
struct
type is declared. C99 has a special construct for such things, called flexible array member of astruct
:You could do something like
You may then allocate such a beast with
and reallocate it with
To use this more comfortably you'd probably better wrap this into macros or inline functions.