Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The meaning of char *p_c = new char['1', '2', '3', '4'];

Tags:

c++

Consider

char *p_c = new char['1', '2', '3', '4'];

Is this syntax correct? If yes, then what does it do?

I don’t know why, but compiler allows this syntax! What will it do with regards to memory? I am not able to access the variable by *p_c. How does one determine the size of and the number of elements present?

like image 390
Neilkantha Avatar asked Nov 29 '22 13:11

Neilkantha


2 Answers

Your code is syntactically valid C++, if rather strange, and I don't think it does what you intended:

new char['1', '2', '3', '4'] is evaluated as new char['4'] due to the way the comma operator works. (The preceding elements are evaluated from left to right, but the value of the expression is that of the rightmost element.)

So your statement is equivalent to char *p_c = new char['4'];

'4' is a char type with a numeric value that depends on the encoding that your platform uses (ASCII, EBCDIC &c. although the former is most likely on a desktop system.).

So the number of elements in the array is whatever '4' evaluates to when converted to a size_t. On an ASCII system the number of elements would be 52.

like image 185
Bathsheba Avatar answered Dec 12 '22 23:12

Bathsheba


The syntax for the new expression you used is something like:

identifier = new Type[<expression>];

In the <expression> above, C++ allows any expression whose result is convertible to std::size_t. And for your own expression, you used the comma operator.

<expression> := '1', '2', '3', '4'

which will evaluate every item in the comma list and return the last, which is '4', and that result will be converted to its std::size_t value, probably (52); So, the code is equivalent to:

char* p_c = new char['4'];
like image 39
WhiZTiM Avatar answered Dec 12 '22 23:12

WhiZTiM