Why use SomeType[1] instead of SomeType* as last member in structs

前端 未结 5 1432
南方客
南方客 2021-01-26 15:59

I saw in the code next statement:

SomeType someVar[1];

Later someVar is used as a pointer to SomeType. Why would one

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-26 16:59

    1. SomeType someVar[1]; allocates memory on the stack and it gives you a block/function scoped variable. So it will be automatically destroyed when it is out of the block/function.

    2. SomeType* someVar; is a pointer (to nothing meaningful yet), so it doesn't allocate any for SomeType. However if you have something like this:

    SomeType* someVar = malloc(sizeof(SomeType));

    of equivalent:

    SomeType* someVar = new SomeType(...);

    Then that is memory allocation on the heap. So it is not destroyed when out of scope and it needs to be destroyed manually by free or delete.

提交回复
热议问题