2

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.

Columbo
  • 60,038
  • 8
  • 155
  • 203
FrozenHeart
  • 19,844
  • 33
  • 126
  • 242

2 Answers2

5

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.

Columbo
  • 60,038
  • 8
  • 155
  • 203
1

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';
Anonymous
  • 2,122
  • 19
  • 26
  • Although this feature indeed exists in some implementations, this is not a dynamic allocation of an array using `new`. – didierc Nov 16 '14 at 13:30