Can I initialize an array with parentheses?

Sometimes, I made a typo in one place of my program code:

int a = 10; char* b = new char(a); 

The error is obvious: I wrote () instead of []. The strange thing is ... the code compiled fine, it worked fine in the debugger. But the compiled .exe outside the debugger crashed an instant after the function with these lines was executed.

Is the second line of code really legitimate? And if so, what does this mean for the compiler?

+6
source share
3 answers

This is the only char with a numeric value of a , in this case 10 . Pointers not only point to arrays, you know.

+10
source

You select one char and assign it a value from a . It does not allocate an array at all.

It is the same as calling the constructor in a new expression for any other type:

 std::string* s = new std::string("foo"); int* i = new int(10); std::vector<std::string>* v = new std::vector<std::string>(5, "foo"); 
+5
source

char t(a) creates a local char initialized with the value of a .
new char (a) creates a dynamically allocated char initialized with the value of a .

+2
source

Source: https://habr.com/ru/post/901315/


All Articles