Reputation: 20746
Does the following construction valid according to the C++ standards and what can I do with the arr after this statement?
char* arr = new char[];
Thanks in advance.
Upvotes: 2
Views: 219
Reputation: 60979
No, this is not allowed. The grammar for new-expressions in [expr.new]/1 specifies
noptr-new-declarator:
[
expression]
attribute-specifier-seq opt
noptr-new-declarator [ constant-expression ] attribute-specifier-seqopt
Clearly there is no expression between the brackets in your code. And it woudn't make sense either: How could you allocate an array of unknown length?
If you need an array whose size is to be changed dynamically, use std::vector
.
Upvotes: 5
Reputation: 2172
C++ compiler offen defines extension allowing to declare array of size = 0. Usualy it can be useful for declaring last field in a structure so you can choose length of such array during structure allocation.
struct A
{
float something;
char arr[];
};
So if you like to allocate such A with let say arr to have 7 elements, you do:
A* p = (A*)malloc( sizeof(A) + sizeof(char)*7) ;
You should note that sizeof(A) is equal to sizeof(float), so for compiler your arr field is 0 sized.
Now you can use your arr field up to 7 indexes:
p->arr[3]='d';
Upvotes: 1