Dynamically Allocating a Struct within a Struct

后端 未结 3 2042
迷失自我
迷失自我 2021-02-09 21:08

I am dynamically allocating a struct which has a different struct as a member:

struct a {
   // other members
   struct b;
}

struct b

3条回答
  •  忘了有多久
    2021-02-09 21:46

    The difference is really equivalent to any other situation where you're comparing "automatic" and "dynamic" allocation.1

    In terms of a guide as when you should use a pointer member, I would say that you should avoid it unless there's a good reason not to, due to the programmer overhead in dealing with manual memory management (and the bugs that it inevitably leads to).

    An example of a good reason would be if you needed your struct a to refer to an existing struct b.


    1. "automatic" is the term used in the C standard for this sort of allocation, because the memory is cleaned up automatically.

提交回复
热议问题