2005 wrote:
[...]
Thanks, Santosh, Richard & Ben,
The issue was missing "i++" - I had actually replaced the "m" with
MAX;
Just a minor point. Your malloc() call in the revised code looks like:
int *ptr = malloc(MAX * sizeof (int));
You might consider instead:
int *ptr = malloc(MAX * sizeof *ptr);
This form ensures that sizeof yields the correct size even if the type
of ptr happens to be changed.
BTW: what is the deal about size_t num_ints = MAX; // MAX is already
defined to be 10 - the code runs w/o that line too.
No idea. If the code runs without that line, then why did you include
it?
As an aside, a name like 'num_ints' is more descriptive of purpose
than 'MAX.'
Also what is this "size_t"?
The parameter to malloc() is defined to be of type size_t. This is
because this is the only type in C that is guaranteed to be able to
represent the size of the largest possible object. It's specifically
meant for holding sizes of objects. sizeof also yields a value to type
size_t. It's an unsigned integral type and is usually a typedef for
unsigned long.
So use size_t if the object is specifically for storing the size of
other objects. OTOH, it's a bit inconvenient in some types of looping
constructs and you need to be careful when mixing it with signed
values in expressions.
Also why do you say "malloc() and friends" ?
Just a short way of alluding to the other allocation functions:
calloc() and realloc().
You can click the link to see/run the code:
http://codepad.org/8Z8Q3pdo
Note that you've not included the stdio.h header in your code at the
above link, though you use the print() function declared in that
header. You should always include the relevant standard header when
using any function it declares. Not doing so in asking for subtle
problems.