Fyodor
Fyodor

Reputation: 2843

Can I really initialize an array with round brackets?

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?

Upvotes: 6

Views: 1818

Answers (3)

Xeo
Xeo

Reputation: 131789

It's a single char with the numerical value of a, in this case 10. Pointers don't only point to arrays, y'know.

Upvotes: 10

Mooing Duck
Mooing Duck

Reputation: 66922

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.

Upvotes: 2

Rob Kennedy
Rob Kennedy

Reputation: 163247

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");

Upvotes: 5

Related Questions