简体   繁体   English

如何为结构分配堆内存?

[英]how do I allocate heap memory for the struct?

I have the following code 我有以下代码

struct USER{

   int human_id_number;

   char first_name_letter;

   int minutes_since_sneezing;

} *administrator;

now I want to allocate heap memory 现在我想分配堆内存

here's my try 这是我的尝试

administrator *newStruct = (administor*)malloc(sizeof(administrator));

not sure if this is right... 不确定这是否正确...

struct USER {
   int human_id_number;
   char first_name_letter;
   int minutes_since_sneezing;
} *administrator;

This isn't just a struct declaration, it's also a variable declaration... it's the same as: 这不仅是一个结构声明,它还是一个变量声明...它与以下内容相同:

struct USER {
   int human_id_number;
   char first_name_letter;
   int minutes_since_sneezing;
};

struct USER *administrator;

So, when you subsequently use sizeof(administrator) , you'll get " the size of a pointer "... which is most likely not what you want. 因此,当您随后使用sizeof(administrator) ,将得到“ 指针的大小 ” ...这很可能不是您想要的。

You probably wanted to do something more like this: 可能想做更多这样的事情:

struct USER {
   int human_id_number;
   char first_name_letter;
   int minutes_since_sneezing;
};

int main(void) {
    struct USER *administrator;

    administrator = malloc(sizeof(*administrator));
    /* - or - */
    administrator = malloc(sizeof(struct USER));

    /* check that some memory was actually allocated */
    if (administrator == NULL) {
        fprintf(stderr, "Error: malloc() returned NULL...\n");
        return 1;
    }

    /* ... */

    /* don't forget to free! */
    free(administrator)

    return 0;
}

sizeof(*administrator) and sizeof(struct USER) will both give you " the size of the USER structure ", and thus, the result of malloc() will be a pointer to enough memory to hold the structure's data. sizeof(*administrator)sizeof(struct USER)都将为您提供“ USER结构的大小 ”,因此malloc()的结果将是一个指向足以容纳该结构数据的内存的指针。

struct USER{
    int human_id_number;
    char first_name_letter;
    int minutes_since_sneezing;
} *administrator;

This defines administrator as a pointer variable. 这将管理员定义为指针变量。 But, from the other code 但是,从其他代码

administrator *newStruct = (administor*)malloc(sizeof(administrator));

It seems you want to use that as a type. 看来您想将其用作类型。 To do so, you can make use of the typedef. 为此,您可以使用typedef。

typedef struct USER{
    int human_id_number;
    char first_name_letter;
    int minutes_since_sneezing;
} administrator;

and then use 然后使用

administrator *newStruct = (administrator *)malloc(sizeof(administrator));

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

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