DEV Community

Pointers

tyrael on February 26, 2024

and Pointers that point to Pointers, and Pointers that... There may be reasons to switch out of computer science, but pointers isn't on...
Collapse
 
pauljlucas profile image
Paul J. Lucas

References were added to C++ to make operator overloading have a natural looking syntax and to pass large objects efficiently — nothing to do with dereferencing.

You don't need to cast the return value of malloc(). C allows a void* to be implicitly cast to T* for any T without warning.

Collapse
 
if-els profile image
tyrael • Edited

Oooh I didn't know about the first part (it reasoned well in my head), and for the casting of malloc I did mention that it's only necessary in C++, but a good habit in C.

Collapse
 
pauljlucas profile image
Paul J. Lucas • Edited

In C++, you generally should use new, not malloc. The only reason to use malloc in C++ is if you have a mixed C/C++ program and C++ code needs to allocate memory that's free'd by C code.

There really is nothing gained by casting malloc in C. There are many things you can do in C that are good habits, but that's not one of them.