Allocating memory for a Structure in C

后端 未结 7 1484
清酒与你
清酒与你 2020-12-12 17:10

I\'m tasked to create a program which dynamically allocates memory for a structure. normally we would use

x=malloc(sizeof(int)*y);

However,

相关标签:
7条回答
  • 2020-12-12 18:09

    I believe, when you call sizeof on a struct type, C recursively calls sizeof on the fields of the struct. So, struct st *x = malloc(sizeof(struct st)); only really works if struct st has a fixed size. This is only significant if you have something like a variable sized string in your struct and you DON'T want to give it the max length each time.

    In general,

    struct st *x = malloc(sizeof(struct st));
    

    works. Occasionally, you will run into either variable sized structs or 'abstract' structs (think: abstract class from Java) and the compiler will tell you that it cannot determine the size of struct st. In these cases, Either you will have to calculate the size by hand and call malloc with a number, or you will find a function which returns a fully implemented and malloc'd version of the struct that you want.

    0 讨论(0)
提交回复
热议问题