Hi all:

The function malloc returns a void* pointer, and so I need to explicitly use type cast e.g.: (struct*)malloc(sizeof(Message_from_server));
I am wondering if it is a legal expression or at least, I should give it a tag name like (struct*message_from_server)malloc(sizeof(Message_from_server));

Thanks

No you cannot do that and you shouldn't even typecast malloc.

If you are compiling a C program as C++ (with .cpp extension instead of .c extention), then you will have to typecase malloc because the compiler is compiling it as a c++ program, and c++ requires the typecase. If, on the otherhand, the file is *.c extension, then no typecase is necessary (permissible but not necessary).

The correct typecast is (see place ment of the asterisk)

// C example
(struct message_from_server*)malloc(sizeof(struct Message_from_server)); 

// C++ example (keyword struct not necessary)
(message_from_server*)malloc(sizeof(Message_from_server));
Member Avatar for iamthwee

Question?

Should you be using malloc in c++, isn't it frowned upon?

Question?

Should you be using malloc in c++, isn't it frowned upon?

Yes -- but it can be much more serious problem that just "frowned upon" because malloc() does not call class constructors or destructors.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.