Array question

While reading my book it says this "Arrays can also be allocated dynamically, in which case the size of an array can be determined at run time, rather than at compile time."

and then it shows this snippet of code.

1
2
 char * buffer;
 buffer = new char[maxsize];


What exactly is it trying to show me here?
Last edited on
The word new is used to allocate memory, based on a type, and it returns a pointer to the memory allocated.

Thus, it can be used to allocate memory for an array, for example, and it can do so from a value you get at run time (the user can input the value, for example). Its paired with delete, which frees the memory.


http://www.cplusplus.com/doc/tutorial/dynamic/
So if I'm reading this right. The purpose for new is to be able to use memory and then free it as soon as the program is executed with delete?
Last edited on
Not exactly.

Lets say that you are making a program to... edit text.

Now, when you type in text, how much space do you need to store it as the user inputs it? You most likely will not know, since the user can type in one single line of text, or, write a whole book.

If you hardcode the size of the text space in your program, it becomes inneficient. You could make a char buffer[100000], and it would most surely waste space on a lot of occasions, as well as it could be insufficient on another.

So, instead of hardcoding, you can allocate and deallocate memory during the execution of the program. Your code could allocate a buffer of char[1000], and while the user types in, IF this space is lets say 90% full, you can use new and allocate more buffers. You cant do the same by normal variable declarations.


Even better, you can create an object to handle that for you... C++ classes vector and list implements this, for example.
Last edited on
Thanks shyoninja I think I understand now.
Topic archived. No new replies allowed.