Link to home
Start Free TrialLog in
Avatar of Dargie
Dargie

asked on

C Array Question

Is there a good way to calculate the number of elements in a malloc'd array?

I need to implement a function that accepts a pointer which is the malloc'd array and returns the number of elements in the array.
ASKER CERTIFIED SOLUTION
Avatar of yoren
yoren

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Dargie, how are you going to malloc the array?
Aren't you going to base it on the number of elements you need to put in the array?
An easy way is to just keep track of how much you malloc and/or put in.

Are you using structures or something of a consistent size?
If so, you can divide the size of the malloc'd array by the size of one data element.  That will tell you how much you have in the array.

Yoren also has two workable ideas.
Avatar of snoegler
snoegler

If you use malloc(), you can use _msize() to get the size in bytes of the originally allocated block. Is this what you're searching for?

BTW: I cannot check right now, but i suppose this is not portable :)
BTW again: I supposed you use MSC/MSVC ...
Avatar of Dargie

ASKER

I can't keep track of the malloc because this needs to be a function that returns the size of an array based upon the array passed.  Yoren's 2nd idea seems to be the only workable solution.  I will malloc 1+ the size of the array needed and append a sentinal value and then loop through until this value is encountered.
Avatar of Dargie

ASKER

They only workable solution.