In article <clcm-20080328-0003@[EMAIL PROTECTED]
>, shofu_au@[EMAIL PROTECTED]
()
wrote:
> How do you determine the number of elements in a dynamically allocated
> variable, without passing the number or having a global variable.
You can't. C does not provide this information.
You need to understand that sizeof is a strictly compile-time operation,
and cannot tell you things whose answers could be determined at
run-time. And the size of dynamic memory allocations is determined at
run-time, when the malloc call is executed. The fact that you have given
a literal size in the source code does not help at all.
Some implementations of malloc will store the size in ways that can be
accessed by means of pointer arithmetic on the address, but these are
not part of the language, and are in no way constrained to work in the
same manner across different operating systems, compilers, or run-time
libraries. Using them means you will, at some awkward future time, find
yourself in deep trouble. So don't.
If you are starting on the architecture of a complex system, it may be
worth creating a memory allocation scheme of your own on top of malloc,
and such a system can provide what you're asking for - there are many
possible ways to do it - but C does not.
--
John Dallman, jgd@[EMAIL PROTECTED]
HTML mail is treated as probable spam.
--
comp.lang.c.moderated - moderation address: clcm@[EMAIL PROTECTED]
-- you must
have an appropriate newsgroups line in your header for your mail to be
seen,
or the newsgroup name in square brackets in the subject line. Sorry.


|