2

Creating an array can be done both of these ways? But isn't all an array is the beginning of the array address and allocate enough bytes for the type. So my question is what's the difference either using a pointer to an array of bytes or using just the first option?

int numbers[10];

int* num = new int[10];
or
int* num = new int(10);
1
  • There are several duplicates, but I'm too lazy to go and find them. Commented Dec 20, 2010 at 1:44

2 Answers 2

4

Your second version there declares a pointer to an integer initialised to 10. That's not an array.

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

Comments

4

int array[10]; has two different behaviors. Used inside a function, it will allocate 10 uninitialized ints on the stack. Outside a function, it will allocate 10 zero-initialized ints in BSS memory.

new int[10]; allocates ten uninitialized ints on the heap.

new int(10); allocates a single int on the heap, with value 10.

1 Comment

int array[10] has a third meaning inside a parameter list. There and only there, it is just syntactic vinegar for int* array. That is, you cannot pass arrays by value in C++.

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.