Occasionaly, I've made a typo in one place of code of my program:
int a = 10;
char* b = new char(a);
Error is obvious: I've written () instead of []. The strange thing is... code compiled ok, it ran in debugger ok. But compiled .exe outside of debugger crashed a moment after function with these lines was executed.
Is second line of code really legitimate? And if it is, what does it mean to compiler?
It's a single char with the numerical value of a
, in this case 10
. Pointers don't only point to arrays, y'know.
You're allocating a single char
and assigning it a value from a
. It's not allocating an array at all.
It's 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");
char t(a)
creates a local char initialized to the value of a
.new char (a)
creates a dynamically allocated char initialized to the value of a
.
来源:https://stackoverflow.com/questions/8098922/can-i-really-initialize-an-array-with-round-brackets