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.

5
  • It's invalid in all standards. What would be the semantic? Commented Nov 16, 2014 at 13:17
  • 1
    I think the exception that could make that valid would be user-defined placement new, where user-defined args are empty; but in that case, you'd need to pass the address, so, nope. Commented Nov 16, 2014 at 13:18
  • 2
    I think what you may be looking for is std::vector Commented Nov 16, 2014 at 13:18
  • @didierc idk, I just saw this code in the C++ project Commented Nov 16, 2014 at 13:25
  • Have you tried to compile it? Commented Nov 16, 2014 at 13:31

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How is expression defined?
@BartekBanachewicz It's anything that's not a statement. As that isn't very helpful: stackoverflow.com/questions/3846727/…
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';

1 Comment

Although this feature indeed exists in some implementations, this is not a dynamic allocation of an array using new.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.