Wednesday, 17 June 2009

Initialising Arrays while doing 'new'

The example below shows how to initialise the array when you are dynamically alocating the memory with new:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

int
main()
{

//int* x = new int(10); - Common Bug for Array allocation
int *x = new int[5]; // Memory UnInitialised
int *y = new int[5]();

for
(int i = 0; i < 5; i++)
{

cout<<"x["<<i<<"]="<<x[0]<<endl;
cout<<"y["<<i<<"]="<<y[0]<<endl;
}


//delete x; - Another Common bug
delete[] x;
delete
[] y;
return
0;
}



The output is as follows:

3 comments:

  1. I could not verify the said behavior on g++ 4.1.2 on Linux. The array of ints gets zero initialized properly in both the cases. Even for class types the default constructor is invoked in both the cases. It does not make sense to me to provide differential treatment (syntax wise) to basic types and class types (imagine a function template that allocates an array of T). MS VS2008 is probably going nuts here.

    ReplyDelete
  2. Hi Sumant,

    I am not surprised if this is Microsoft Visual Studio specific feature. I do say on the main page of the Blog that the code is only tested on Visual Studio 2008. Love it or loathe it, Visual Studio is used in many companies i work(ed) with and we develop code specific to windows.

    Cheers!

    ReplyDelete
  3. Hi Sumant,

    I just tried this code using the Cygwin g++ compiler and was able to compile without problems. The good thing is the initial values were 0 for both initialised and uninitialised case.

    Cheers!

    ReplyDelete