What's the difference between new char[10] and new char(10)

Viewed 97953

In C++, what's the difference between

char *a = new char[10];

and

char *a = new char(10);

Thanks!

6 Answers

[10] defines an array where as (10) assigns a value to the newly created (single) character.

If you want to declare an array of size 10 in C and by mistake you define char a(10), compiler would throw a syntax error, so you get to fix it. But in C++, it will compile fine and your program may crash while accessing say a[1] or while deleting a.

So in C++, its always better to use vector rather than dynamically allocated arrays. I hope you got the point.

Related