Why do I have to use malloc when I have a pointer to a struct?

后端 未结 5 416
眼角桃花
眼角桃花 2021-01-23 10:55
 struct element {
     int val;
     int z;
 };
 typedef struct element ELEM;

Look at this example:

 int main()
 {

    ELEM z;
    z =         


        
5条回答
  •  北海茫月
    2021-01-23 11:32

    Declaring a pointer doesn't create anything but a pointer. Gotta have something for it to point to, which is what malloc gives you.

    Alternatively, you could have created the struct on the stack (a.k.a. "automatic storage"):

    ELEM z;
    ELEM *p = &z;
    (*p).val = 3; // Also could be written as p->val = 3;
    printf("%d",(*p).val);
    

    BTW, your pointer code has an error, in that it leaks (i.e. loses track of) the first allocated struct:

    ELEM *p;
    p = (ELEM*)malloc(sizeof(ELEM));
    (*p).val = 3;
    p = (ELEM*)malloc(sizeof(ELEM)); // <- leak here: pointer to old struct lost.
    printf("%d",(*p).val);
    

    Deleting the second malloc fixes the problem. A full, fixed-up version that looks more like code you'd see in use:

    ELEM *p = (ELEM*)malloc(sizeof(ELEM));
    p->val = 3;
    printf("%d\n", p->val);
    free(p);
    

    Every malloc should have a free, unless your program releases it memory by terminating. And even then, it's nice to have the free.

提交回复
热议问题