简体   繁体   English

结构数据的C内存分配顺序

[英]C memory allocation sequence for struct data

I am reading a C scripts written by someone else. 我正在阅读别人编写的C脚本。 I don't understand this memory allocation part. 我不了解此内存分配部分。

lda_suffstats* ss = malloc(sizeof(lda_suffstats));
ss->class_total = malloc(sizeof(double)*num_topics);
ss->class_word = malloc(sizeof(double*)*num_topics);

where lda_suffstats is a self-defined structure, 其中lda_suffstats是一个自定义结构,

typedef struct
{
double** class_word;
double* class_total;
double alpha_suffstats;
int num_docs;
} lda_suffstats;

My question is regarding the first line of memory allocation. 我的问题是关于内存分配的第一行。 What is the size of lda_suffstats? lda_suffstats的大小是多少? Shouldn't the memory for each of its component be allocated before itself? 难道不应该为每个组件分配内存吗?

You can know how big lda_suffstats will be before you actually have one, just like you know how big of a bag you need to have with you in order to fit two cartons of milk and a dozen eggs. 您可以在实际拥有一个lda_suffstats之前知道它有多大,就像您知道为了容纳两箱牛奶和一打鸡蛋需要携带多大的袋子一样。 A size of lda_suffstats is a sum of sizes of double** , double* , double and int , no more, no less. lda_suffstats的大小是double**double*doubleint的总和,不多也不少。 They are not independent components, they'll all use the memory of the lda_suffstats . 它们不是独立的组件,它们都将使用lda_suffstats的内存。 Now, the first two are pointers, which means the associated value is not right there but only pointed to, and allocating the target of the pointers is what the other two malloc lines are about. 现在,前两个是指针,这意味着关联的值不在那里,而仅指向该指针,而分配指针的目标就是另外两个malloc行。

lda_suffstats has four fields with the types of double** , double* , double , and int . lda_suffstats具有四个字段,类型为double**double*doubleint The size of each of these is known at compile time. 它们的大小在编译时是已知的。 The sum of their sizes gives the size of lda_suffstats . 它们大小的总和给出了lda_suffstats的大小。 The amount of memory allocated to the pointers does not change this because that memory is allocated outside of the struct . 分配给指针的内存量不会改变,因为该内存分配在struct之外。

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

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