Because sizeof
is a compile-time calculation, not a run-time one. And your array size is not known until run-time.
sizeof
does not know anything about where the pointer points to, so it doesn't matter how big of a buffer you allocated, or even that you allocated a buffer at all. You can even do:
data = NULL;
x = sizeof(*data);
Because it's calculated at compile-time, there is no null-pointer dereferencing.
sizeof
only looks at the datatype you pass in, not the data itself. In this case, string*
, which is the same size no matter where it points to.
You have a few options to make this "work":
- Use a statically-sized array (e.g.
string data[50];
) where you can use your sizeof
idiom, but of course you get all the standard limitations of static arrays then.
- Continue to dynamically allocate using
new
, but just store the array size and pass it around wherever you need it.
- Preferred: Use
std::vector
for arrays -- this is basically the best of all worlds.