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

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

提交回复
热议问题