Get up to 80 % extra points for free! More info:

Discussion – Lesson 2 - Dynamic memory management in C++

Back

 

Comments
Avatar
Manoj Madushantha:7/3/2021 8:12

so new keyword dynamically allocated memory why is that a number 10 given to array ?
int* array = new int[10];

this means 10 items. how about number of items are not knowing?

 
Reply
7/3/2021 8:12
Avatar
Richard Bleier
Creator
Avatar
Replies to Manoj Madushantha
Richard Bleier:7/5/2021 5:37

Hi Manoj,

the length of a dynamically allocated array doesn't need to be passed as a constant value (e. g. value 10 or 15), it can be passed just as any normal integer variable (e. g. byte, short, int etc...), for example:

int len = 10;// the variable could be of any integer data type as long as the value fits in its range
int* array = new int[len];

This way you can create an array of any desired length you need it to be.

If you run into a situation where you need the array to be able to expand itself (e. g. when you're adding new items to a warehouse stock), there is a container called vector , but that's a little advanced topic.

If you have any other questions regarding this or similar topic, feel free to ask.

 
Reply
7/5/2021 5:37
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

2 messages from 2 displayed.