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?
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.
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.
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).
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With