I have a problem with finding the length of an array at run time and can't understand what is going wrong.
NB: someObject is a class which need not be shown in the question, any class at all.
#define arraylen(x) (sizeof(x)/sizeof(x[0]))
void failingFunction(int count)
{
someObject *theArray
theArray = new someObject[count];
fprintf(stderr,"length = %d",arraylen(theArray));
}
void workingFunction(int count)
{
someObject theArray[3]
fprintf(stderr,"length = %d",arraylen(theArray));
}
The working function will give me the correct size via the macro, the failing function never gives me anything close to the right size. Assume that "count" is not known when I need to find the size, the code is just an example...
What am I missing, thanks in advance ?
Obtaining the size of an array in C++ at runtime?
I don't think it has anything to do with vectors - at least the explanation of why failingFunction() is failing. It is failing because, to the compiler, "theArray" is just a pointer, and sizeof( theArray ) will yield the size of long, i.e., the integer used to store the address. It does not matter whether theArray is the beginning address of an array, C++ cannot evaluate the size of that array, because it was allocated by new.
To better understand why, let us look at this example:
Probably you know that you if you allocate an array using new[] as you have done, you should use delete [] to prevent memory leak. But if you have allocated using just new (not the parentheses), then you should free the memory using delete (and not delete []).
So what will happen if you allocate using new [] and while freeing, use just delete instead of delete []?
Answer: It will leak memory, only the first element will be freed, the rest won't be freed.
So why does not either the compiler or the runtime libraries give an error when you use delete instead of delete[]?
Answer to that question is - it does not know whether you are doing the right thing or not! Because it does not know the goddamn size of the array! It does not know whether the size is 1 or 3 or 100. So it cannot blame you fearing that you might be knowing what you are doing, and the blame might leave it embarassed!
The whole point was to prove that it does not know the size. And if it does not know the size, how will sizeof() work? It won't!
That is the explanation of why it is not working. As to how you can make it work, that question is equivalent of asking - how do we know the size of an array allocated by new []?
Yes, you can do that by using container classes like vectors, there is not straightforward way. I have always wondered that the method delete[]() somehow knows what the size is, so why not expose another method like size() to return it to the developer?
id cards
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment