Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
fyodorananiev Avatar asked Nov 11 '11 19:11

fyodorananiev


People also ask

What are the different ways of initializing array in C?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.

How do you initialize an array with an entire value?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

What is array [] C++?

Arrays in C++ An array is a collection of elements of the same type placed in contiguous memory locations that can be individually referenced by using an index to a unique identifier. Five values of type int can be declared as an array without having to declare five different variables (each with its own identifier).


2 Answers

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

like image 136
Xeo Avatar answered Nov 13 '22 05:11

Xeo


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");
like image 22
Rob Kennedy Avatar answered Nov 13 '22 05:11

Rob Kennedy