0

What is the difference between these three lines in C++?

int *p= new int;
int *p= new int[10];
int *p = new int[];

We are already dynamically declaring the memory to pointer variable p, why is it required to specifically mention pointer array size?

1
  • and the last one is an error: expected primary-expression before ']' token int *p = new int[]; Commented Sep 23, 2017 at 1:40

1 Answer 1

2
int *p = new int;

This allocates enough memory for a single object of type int and stores a pointer to it in the pointer-to-int variable p. This means that *p refers to a valid int object.

int *p = new int[10];

This allocates enough contiguous memory for ten objects of type int and stores a pointer to the first int in the pointer-to-int variable p. This means that p[0] through p[9] refer to valid int objects.

int *p = new int[];

This statement is syntactically incorrect. It is not valid C++, and therefore has no meaning.

... why is it required to specifically mention pointer array size?

How else is the memory allocator supposed to know how much memory to allocate if you don't tell it how many ints you need room for?

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

1 Comment

Also, it should be noted that new for a single object must be matched with delete for a single object, and new[] for an array must be matched with delete[] for an array. new[] stores the array count in such a way that delete[] knows how many objects to destruct (if needed) before freeing the underlying memory block.

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.