Alex said:
Nils said:
Alex wrote:
I saw the topic of "wired code " about "point to array" and know a
little about it. But I am still confused about the question below:
I define a point to array "b"
int (*b)[100];
then I locate the memory to b,using "malloc"
b= (???) malloc( 10*sizeof ( *b )
Don't cast the return value from malloc.
b= malloc( 10*sizeof ( *b ) ;
If you're asking what the type of b is it's an int(*)[100];
Here,if I want to convert the type by force, which shall I use?
I use:
b=(int**)malloc(10*sizeof(*b));
the code can compile, but there is a warring "assignment from
incompatible pointer type"
That's what you get when you cast to something you should not.
Don't do that.
Thanks for your quickly reply.
But another question, Why "Don't cast the return value from malloc"?
I just begin to have a job, and I see some code written by colleague
using "cast" in malloc.
appreciate for your reply
Because
a) it is not necessary in C:
malloc() returns void * which can be converted into every kind
of object pointer implicitly.
b) it can mask an error:
If you failed to #include <stdlib.h> then you will hopefully
get a warning or error because then your compiler has to assume
that the undeclared function malloc() returns int -- and int has
no automatic conversion to a pointer type.
If you cast, then you tell the compiler to shut up.
The return value of malloc() is taken and interpreted as int
and then converted to an (int **) which is wrong in your case.
Even uglier: There are systems where this process leads not always
to success and not always to abysmal failure, so your programme
fails sometimes but not always. Ideally it works in the debugger
or when you add printf()s to find the error...
If your colleague does it out of habit, then question this habit.
If your colleague does it "so it compiles with a C++ compiler",
then know fear -- either write C++ or C but not both. Semantic
subtleties are out to bite you.