How to initialize memory with a new operator in C++?


The new operator in C++ is defined for allocating memory and not initializing. If you want to allocate an array of type int with the new operator, and you want to initialize them all to the default value(ie 0 in case of ints), you can use the following syntax −

Syntax

new int[10]();

Note that you simply must use the empty parentheses - you can't, for example, use (0) or the other expression that is why this is only helpful for default initialization.

There are other methods of initializing the same memory using fill_n, memset, etc which you can use to initialize objects to non default values. 

example

#include<iostream>
int main() {
   int myArray[10];
   
   // Initialize to 0 using memset
   memset( myArray, 0, 10 * sizeof( int ));    
   
   // Using a loop assigns the value 1 to each element
   std::fill_n(array, n, 1);    
}

Updated on: 19-Jun-2020

771 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements