简体   繁体   中英

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.

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.

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 struct USER{
    int human_id_number;
    char first_name_letter;
    int minutes_since_sneezing;
} administrator;

and then use

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

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