Hi, I was recently reading a tutorial on C++ and I had a question about dynamic memory.

The first paragraph of the tutorial stated the following:

"Until now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program. But, what if we need a variable amount of memory that can only be determined during runtime? For example, in the case that we need some user input to determine the necessary amount of memory space.

The answer is dynamic memory, for which C++ integrates the operators new and delete."

It talks about the following

int * bobby;
bobby = new int [5];

and

delete pointer;
delete [] pointer;

My question is that even without using the new and delete can I not use the basic approach to dynamic memory. For example can I not just do this:


int i;
int array[i];

cin>>i;

now we have an array with size i, and that will be adjusted according to the input given.

So, what is the use of using "new" operator?


THANK YOU!

Dani AI

Generated

A few focused clarifications that address the confusion in the thread and add practical, modern advice.

The built-in C++ array syntax requires the size to be known (a compile-time constant) in standard C++. Declaring an automatic array with a runtime value (the pattern tried) is not portable C++ and can produce undefined behavior if the value is uninitialized; some compilers let it through as an extension, but that should not be relied on. See the language rules for arrays for the formal wording: .

What dynamic allocation gives you is two things: a runtime-determined amount of storage, and control over the lifetime of that storage. Memory obtained from the free store (via the language allocation facility) can be sized at run time and can outlive the scope where it was requested; automatic (stack) storage cannot. If you use manual allocation you must also pair it with the correct deallocation form; mismatches or failures to free memory lead to undefined behavior and leaks. The mechanics are explained here: dynamic allocation in C++.

For nearly all real code, prefer standard library solutions instead of raw allocation. A resizable sequence should be std::vector, and single objects that need dynamic lifetime are better held by smart pointers (std::unique_ptr/std::shared_ptr). These give exception-safe, leak-free behavior and clearer intent: std::vector, std::unique_ptr.

To the follow-ups: assigning a new value to an array element or to a variable simply overwrites the stored value — there’s no special “clearing” step required, but always stay inside bounds and initialize storage before reading it. For stopping the console, avoid OS-specific system calls; use the IDE/run settings or a simple input-wait as a portable alternative (as suggested). Tools such as Valgrind can help catch leaks and invalid accesses while you learn.

Recommended Answers

All 7 Replies

When your program is running and you need to allocate memory WHILE the program is running, dynamic memory allocation is the way to go.

Think of how restrictive programs would be if they always had to perform on limited memory.

There are more benefits to dynamic memory, but this is just one of them.

Correct me if am wrong but i dont think that will work well. Initially, the array has i elements which are not initializes. Even if you initialized i to say 5, I dont think the outcome of the user input would affect the array declaration.

Dynamic memory is good in a way that the program can grow and shrink. You will need the new operator to allocate new memory for the program and the delete operator to delete it so that nothing is wasted. In arrays, if you declare something like "array[5]", memory will be allocated for that array even if it is not used. Well that is the most I can think of to put this explanation clear and I hope it helps

Okay, thank you for replying. According to what I have read and tried out, what I seem to understand is that if I do it the way i'm saying by declaring array and i separately, it only could lead to problems. Basically it is possible that it uses more memory than needed while the dynamic memory method allows for proper memory allocation. Perhaps when I use the new and delete operators more often I will get a better understanding of why it is better to go that way rather than the way I stated. Thanks again.



ALSO

I had two other questions not sure if I should open a new thread, anyways ill first ask here.

1. If I declare an array, for example array[2]. Then I specify array[0]=1, array[1]=2.

Can I later in my program say array[0]=2 WITHOUT somehow clearing the previous "1" which was in its place.

Will this lead to problems sometime?


2. I read that if possible avoid system("pause"). I am currently using Dev C++ and I do not know any other way to stop the program from shutting down automatically after I run it without using the system("pause") method. Is there a better or more suitable way I should be doing it? And if I were to copy and paste the source from Dev C++ to for example Visual Basic will it affect the program (will the system("pause") have a different affect on it)?

Thanks, this is a great forum with great people!!

For question number 1 - is it possible to assign your array with a variable later?

Yes it is, because your array will receive "garbage" information until you give it values.

For example, you allocate memory for the array (either dynamically or from the stack - your call) and decide to display that indice of the array using cout. You'll realize that the number can range from 0 to the highest number that your data type can hold. For example..

int myIntArray[5];

cout << myIntArray[0] << endl;

Will display any particular number that an int can be (it's random, but only random once) because what I did was assign my array to have enough memory for 5 ints. I never gave it any values, so the values in the array (initially) will be what programmers call "garbage."

To answer your second question, replace system("pause") with this--

cin.get();

That will pause your program in most cases, however you should probably read the link "How do I flush the input stream" made by the expert meanie Narue. It will help you around some stream problems you will encounter as you learn c++.

Alright, thanks for the information but for the first question i was asking if I give the array a value for example

1.
2.
3. int myIntArray[5];
4. myIntArray[0]=1;
5. cout << myIntArray[0] << endl;
6. myIntArray[0]=2;

So basically can i give a variable another value afterwards? Even if it was not an array for example a simple int variable; and I give the variable=1 then later in the source I say variable=2. So "am I allowed" to do this. Does it matter that there was a 1 before , or will it just erase it and put in 2 in its place.

and I will definitely read the input stream thread. Thanks

well you can do that with anything. Be it array. the "=" operate assigns a value to something so ofcourse the original value will be changed. Hope that helps

In order to request Dynamic memory we use the operator new.System dynamically assigns space to elements in case of array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.