简体   繁体   中英

C memory allocation sequence for struct data

I am reading a C scripts written by someone else. 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,

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? 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. A size of lda_suffstats is a sum of sizes of double** , double* , double and int , no more, no less. They are not independent components, they'll all use the memory of the 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.

lda_suffstats has four fields with the types of double** , double* , double , and int . The size of each of these is known at compile time. The sum of their sizes gives the size of lda_suffstats . The amount of memory allocated to the pointers does not change this because that memory is allocated outside of the struct .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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