Home > Software engineering >  nullptr and new keyword
nullptr and new keyword

Time:03-16

I'm learning C and kind of confused why the instructor keeps initializing a pointer to nullptr instead of just directly allocate memory on the heap

int *new_storage {nullptr};
new_storage = new int[size];

why cant he just do:

int *new_storage = new int[size];

is there any advantage of initializing a pointer to nullptr prior to memory allocation?

CodePudding user response:

Instructors are people and they have their own habits. Doing it the second way is considered better by just about everyone, and if you asked him or her about it, you'd probably get agreement.

Of course, get this use of raw pointers out of your system. You need to know how it works, but modern C uses smart pointers. You'll want to transition to them as soon as you can do everything using raw pointers.

CodePudding user response:

While you are learning any skill, it can be useful to take small steps. The challenge for every instructor is to figure out how small these steps should be.

In this case, I would agree with you: this is overdoing "small steps". But the bigger critique is that the instructor is teaching new[] to beginners. For the last 25 years or so, the recommended simple approach is std::vector<int>.

In a follow-up course, an instructor could teach how to use new[] to implement your own Vector class, but that should be for students who can already use std::vector<int>.

  • Related