JS wrote:
On this page under "Malloc":
http://www.le.ac.uk/cc/tutorials/c/ccccstrc.html
I found this:
ptr = (*int) malloc(sizeof(int)*N)
But when I try to compile it in a main method I need to write:
int *ptr;
ptr = (int *) malloc(sizeof(int));
why does the example cast like this (*int)
and when I compile I need to write:
(int *)
Because the example is wrong, R-O-N-G, wrong. Even
after fixing the typographical error (as you did), the
example demonstrates poor technique; a far better idiom is
ptr = malloc(N * sizeof *ptr);
"Why is that better?" you ask. First, the cast is
unnecessary: malloc() returns a `void*' value, and this
type converts automatically to and from any data pointer
type. Second, `sizeof *ptr' is better than `sizeof(int)'
because it is guaranteed to be the proper size. That is,
it avoids errors like
short **p = malloc(N * sizeof(short));
.... where `sizeof(short)' should have been `sizeof(short*)'.
This latter error is more insidious when multiple types
are flying around:
struct query_s { ... } *p;
struct response_s { ... } *q;
...
p = malloc(sizeof(struct query_s));
FillInQueryData(p);
q = malloc(sizeof(struct query_s)); /* oops! */
GetResultsOfQuery(p, q);
--
Er*********@sun.com