I saw in the code next statement:
SomeType someVar[1];
Later someVar
is used as a pointer to SomeType
. Why would one
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*).
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.
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.
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.
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
.
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