Code: Select all
curr = ( struct data * ) malloc ( sizeof( struct data ) );
Code: Select all
curr = malloc ( sizeof( struct data ) );
Moderator: Board moderators
Code: Select all
curr = ( struct data * ) malloc ( sizeof( struct data ) );
Code: Select all
curr = malloc ( sizeof( struct data ) );
malloc() returns type void * so the result must be type cast if curr is of a different type. the only affect is to make the compiler happy. there is no runtime differenceRoby wrote:Does anyone know the effect and the difference between these:andCode: Select all
curr = ( struct data * ) malloc ( sizeof( struct data ) );
Thanx...Code: Select all
curr = malloc ( sizeof( struct data ) );
Code: Select all
curr = malloc ( sizeof( struct data ) )
Some compilers will give you a warning and some compilers will give you an error. It's a matter of type safety. The compiler checks to make sure that the return type of a function is compatible with the context it's used in. For your example, it will check if void * is compatible with the type of 'curr'. If the type of curr is 'void *', the compiler will let it go. What if 'curr' is a pointer to a different type? The compiler doesn't know if the conversion is legal. That's why it will give you a warning. By adding a manual type cast, you are telling the compiler that the conversion is safe. There really isn't any more depth to this.Roby wrote:Make the compiler "happy"? So, it's permitted if I write this:instead of the other one, isn't it? Can somebody give me more technical reason what's the effect of doing this? Sorry, just wanna know more...Code: Select all
curr = malloc ( sizeof( struct data ) )
Thanx...
That is not true. If it's a C compiler that you have in mind, you are wrong.kryptolus wrote:Some compilers will give you a warning and some compilers will give you an error...
Code: Select all
struct mystruct *pstrct = malloc( sizeof *pstrct );
Code: Select all
#include <stdlib.h>
Code: Select all
#include <stdlib.h>
int main(void)
{
struct mystrct *pstrct = malloc( sizeof *pstrct );
return 0;
}
Code: Select all
#include <stdlib.h> // yes, I know about <cstdlib> :)
int main(void)
{
struct mystrct *pstrct = (struct mystrct *)malloc( sizeof *pstrct );
return 0;
}
Code: Select all
#include <cstdlib>
Code: Select all
#include <stdlib.h>
Code: Select all
#include <cstdio>
int main(void) { std::printf("Hello, world!\n"); }