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

前端 未结 5 1419
南方客
南方客 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:38

    Because generically speaking they are not the same. The first one defines one element array of SomeType and the other defines pointer to SomeType.

    The first allocates memory for that one element, the other does not.

    In general: sizeof(SOmeType[1]) != sizeof(SomeType*).

    0 讨论(0)
  • 2021-01-26 16:55

    The first can be treated as a pointer to a possibly uninitialized SomeType (initialized if it's a non-POD type). The second is just a dangling pointer.

     SomeType someVar[1];
     someVar[0]; //valid
     *someVar;   //valid
    

    vs

     SomeType* someVar;
     someVar[0]; //invalid
     *someVar;   //invalid
    

    For the second one to work, you'd need to make it point to something valid, so either an existing object (so then there's no point in having the pointer there), or to a new object allocated with new, in which case there's the downside that you have to call delete yourself.

    0 讨论(0)
  • 2021-01-26 16:58

    If you use SomeType*, you will need a new at some point and you will thus have to delete it to avoid leaks.

    Using SomeType[] allocates on the stack and the memory management will be handled for you.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-26 17:01
    SomeType someVar[1];
    

    someVar is an array of type SomeType with 1 element.

    SomeType* someVar;
    

    someVar is a pointer (dangling still, you didn't point it to anything yet) of type SomeType.

    And you can use the name of an array on its own as a shorthand for a pointer to the first element of that array.

    Will Dean

    0 讨论(0)
提交回复
热议问题