new [] syntax I've never seen for zeroing out memory

This works to allocate a new int and initialize it to 5 ...

1
2
3
4
5
6
7
8
9
10
#include <cstdio>

int main()
{
 int* pInt = new int(5);
 printf("pInt[0] = %d\n",pInt[0]);
 getchar();

 return 0;
}


That compiles/runs fine and outputs that *pInt=5. But attempting to extend that type of initialization to arrays doesn't seem to work. With my older MinGW compiler I get this result when attempting to initialize an array of ints all to zero ...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cstdio>

int main()
{
 int* pInt = new int[4](0);
 for(int i=0; i<4; i++)
     printf("pInt[%d] = %d\n",i,pInt[i]);
 getchar();

 return 0;
}

//-------------- Build: Release in Test ---------------

//Compiling: main.cpp
//C:\Code\CodeBlks\Test\main.cpp: In function 'int main()':
//C:\Code\CodeBlks\Test\main.cpp:5: error: ISO C++ forbids initialization in array new
//Process terminated with status 1 (0 minutes, 0 seconds)
//1 errors, 0 warnings 


That's pretty plain English I'd say - "ISO C++ forbids initialization in array new".

However - and I find this bizarre - this compiles/runs perfectly, in spite of the fact that "ISO C++ forbids initialization in array new" ...

1
2
3
4
5
6
7
8
9
10
11
#include <cstdio>

int main()
{
 int* pInt = new int[4]();
 for(int i=0; i<4; i++)
     printf("pInt[%d] = %d\n",i,pInt[i]);
 getchar();

 return 0;
}


If you didn't catch it (and it would be easy to miss), all I did was remove the '0' within the parentheses, i.e., I changed this ...

int* pInt = new int[4](0);

to this ...

int* pInt = new int[4]();

I just couldn't find a reference to that as acceptable syntax. Is it????

If you want a pointer to an array, you do this:

1
2
3
4
5
6
int* pInt = new int[4];
...

// don't forget matching delete[]
delete[] pInt;
pInt = NULL;

I just couldn't find a reference to that as acceptable syntax. Is it????


Yes. It is.

1
2
int* p = new int[5];  // constructs an array of 5 ints, all uninitialized
int* p2 = new int[5](); // constructs an array of ints, all zero'd 


It's a bit confusing, I know. But it's perfectly OK.

It's similar an idea to this:

1
2
int x;  // uninitialized
int z = int();  // zero'd 
I just couldn't find a reference to that as acceptable syntax. Is it????

How about cppreference? http://en.cppreference.com/w/cpp/language/new (look for "If initializer is an empty pair of parentheses")
Last edited on
Thanks guys for the info. I'm more a C coder than a C++ one, and just wasn't sure that syntax was right. I just wasn't familiar with it. I had been using memset() to zero out the arrays, and a friend showed me the []() thing, and I was somewhat taken aback with it having never seen it. Could see it worked, but couldn't figure out if it was ledgit.
Topic archived. No new replies allowed.