Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Confusion on pointers and syntax

0 votes
asked Aug 18, 2021 by Gourab Roy (120 points)
I'm new to c++ programming and have some doubts regarding the syntax.

In c this code is used: A = (int *)malloc(size); where A is a pointer right? and the new array which is formed in the heap right?

In C++ it can be written as: A = new int[size];

Can you please clarify what does the syntax exactly means?

1 Answer

0 votes
answered Sep 22, 2021 by Peter Minarik (84,720 points)

First of all, malloc() and new are both serve similar purposes: allocate new memory on the heap. Both return a pointer to the start address of the allocated memory.

However, they are not interchangeable, as malloc()-ed memory has to be free()-ed while new-ed memory has to be delete-ed.

Another difference is that while malloc() and free() are library functions (#include <stdlib.h>), new and delete are operators on the language level.

If we consider that you want to new an object, not a primitive type, then another important difference is that the new operator calls the constructor of this object and delete calls the corresponding destructor.

There are some more differences, I'll let you read more about the matter here.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...