0

I'm a beginner for C++ and I saw the post here. However, it is very unclear for me what is the benefit of dynamic array.

One advantage is that one can change the length of a dynamic array, here is the code

int *p = new int[10];
// when run out of the memory, we can resize
int *temp = new int[20];
copy(p, temp); // copy every element from p to temp
delete[] p; // delete the old array
p = temp;
temp = nullptr;

Above is for dynamic allocation, it says the array will be on the heap, and need to manually delete it. However, why not use the static array as follow

int array1[10];
int *p = array1;
// when run out of the memory, we can resize
int array2[20];
copy(array1, array2); // copy every elements from array1 to array2;
p = array2;

In this code, we don't need to delete the array1 since it is on the stack area. Here are my question:

what is the benefit of the dynamic array? It seems for me, resizing is not a big issue. People always say the size of static array are fixed, the size of dynamic array is not fixed. Why the size of dynamic array is not fixed. for example, int p=new int[10], the size of p is fixed.

Thanks a lot.

4
  • Do you know about a scope of a variable, life time of a variable? Commented Oct 26, 2020 at 0:21
  • @S.M. not really, it is mean the static array will waste memory if it is under scope. And the dynamic array will be more flexible to delete in the program? Commented Oct 26, 2020 at 0:23
  • Post you've mentioned refers to stack and heap. So try to declare non-global int array[SOME_LARGE_NUMBER] and that probably would fail if you haven't modified stack size. Commented Oct 26, 2020 at 0:32
  • Thanks, How about I create a new array, first int array[LEN1], and then replace with int array[LEN2]. Commented Oct 26, 2020 at 14:18

3 Answers 3

1
int array1[10];
int *p = array1;
// when run out of the memory, we can resize
int array2[20];
copy(array1, array2); // copy every elements from array1 to array2;
p = array2;

In whichever function, or inner scope, array1 and array2 get declared these arrays get automatically destroyed when the function or inner scope returns. Full stop.

This is why this is called "automatic scope". The fact that there may be a pointer to one of the arrays is immaterial. The array will be gone and any attempt to dereference that pointer will result in demons flying out of your nose.

So if you had any grand designs to continue using this array, in some form or fashion, after returning from the function where they get declared, too bad. It's not going to happen.

On the other hand, after newing something, as long as you properly track the pointer to the newed object(s) they can be used anywhere else, until they get deleted. This function, another function, anywhere. Even a different execution thread.

Having said all of that, you should not be using new or delete either. You should be using C++ library's containers which will correctly handle all memory allocation, deallocation, and copying, for you. In this case, you are simply reinventing what std::vector already does for you, and it will actually do it, in some ways, far more efficient than you can do easily on your own. You just call resize(), and, presto, your vector is bigger or smaller, as the case may be. And, in all other respects the vector will be indistinguishable from your array. It will be very hard to tell the difference.

So, use C++ library's containers. They are your friends. They want you to do memory allocation correctly, on your behalf. Modern C++ code rarely uses new or delete, any more. It's important to understand how it works, but 99% of the time you don't really need it.

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

4 Comments

I now know about the memory thing. Thanks for the suggestion.
Can you add some details about the resizing. I often hear that the length of dynamic array can be resized. what is that means? it seem for me int *p = new int[10]; the size of dynamic array p is also fixed. I just mock the first block of code and show that we can also resize the static array as the dynamic one (my second block of code). Thanks.
I don't know what you heard or didn't hear. You are correct that the size of a newed array is fixed. If its size needs to be changed, a new array is created by new, any contents get copied from the old array to the new array, and the old array gets deleted. That's the only way to resize the array. And that's precisely what std::vector will do for you. Why do you want to go through all that trouble, when std::vector already does the hard work for you, all you have to do is call resize()?
Thanks for the note, I'm need to design a reisze() just for a homework.
1

Doing your own dynamic array with new int[20] and delete[] etc, is no doubt good for learning how it all works.

In real C++ programs you would use std::vector. Maybe like this:

#include <iostream>
#include <string>
#include <vector>

int main() {
  std::vector<std::string> lines;

  std::string line;
  while (std::getline(std::cin, line)) {
    lines.push_back(line);
  }

  std::cout << "Read " << lines.size() << " lines of input\n";
}

The reason you would use dynamic allocation is so your program can handle any number of lines of any line length. This program can read four lines or 400,000. The std::vector is dynamic. So is std::string.

1 Comment

Thanks for the note. It seems that my second chunk of code and also do the resizing thing. But it may have another issue since I cannot delete the array1[10] until the program ends. In my mind, the dynamic array means it can have any length. Is that dynamic in dynamic array mean that we can create or delete in any time? No mean that the length of dynamic array is dynamic?
0

I have write a code on static and dynamics array, hope this will help.

#include<iostream>
using namespace std;

int main (){
    //creating the static array .. rember the syntax of it.
    int array[4]= {1,2,3,4}; // size is fixed and can not be changeable at run time.
    
    cout<<"Static Array."<<endl;
    cout<<"Printing using index."<<endl;
    for(int x=0;x<4;x++){
        cout<<"\t"<<array[x];
    }
    
    cout<<endl;
    cout<<"Printing using pointer."<<endl;
    int*ptr= array;
    for(int x=0;x<4;x++){
        cout<<"\t"<<*ptr++;
    }
    //delete [] array ;// error, because we can not free the size from stack
//  array[6]= {1,2,3,4,5,6}; //Error: We can not change the size of static array if it already defined.
// we can not change the size of the static aray at run time.
    
    cout<<endl;
    cout<<"\n\nDynamic Array."<<endl; 
   int n=4;
   //Creating a dynamic Array, remember the systex of it.
   int *array2 = new int [n]; // size is not fixed and changeable at run time.
   array2[0]= 1;
   array2[1]= 2;
   array2[2]= 3;
   array2[3]= 4;
    cout<<endl;
    cout<<"Printing using index."<<endl;
    for(int x=0;x<4;x++){
        cout<<"\t"<<array2[x];
    }
    
    cout<<endl;
        cout<<"Printing using pointer."<<endl;
    int*ptr2= array2;
    for(int x=0;x<4;x++){
        cout<<"\t"<<*ptr2++;
    }
    cout<<endl<<endl<<endl;
    delete array2; //Size is remove at runtime
     cout<<"Chnaging the size of dynamic array at runtime... :)";
    // Changing the size of the array to 10.. at runtime 
    array2 = new int [10]; // Array size is now change to 10 at runtime
   array2[0]= 1;
   array2[1]= 2;
   array2[2]= 3;
   array2[3]= 4;
   array2[4]= 5;
   array2[5]= 6;
   array2[6]= 7;
   array2[7]= 8;
   cout<<endl;
    cout<<"Printing using index."<<endl;
    for(int x=0;x<7;x++){
        cout<<"\t"<<array2[x];
    }
    // free the memory/ heap
    delete [] array2;
    return 0;
}

Output

enter image description here

Comments

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.