英文:
Why do we use Dynamic memory allocation while using arrays in c++
问题
在学习C++中的指针时,我遇到了"数组中的动态内存分配",我们可以像这样执行它:
int *array_ptr {std::nullptr};
size_t size{};
cout << "Enter the size of the array: " << endl;
cin >> size;
array_ptr = new int[size];
但我的问题是,我们可以简单地通过另一种方法来完成这个任务,即:
size_t size{};
cout << "Enter the size of the array: " << endl;
cin >> size;
int array[size] {};
第二种方法将完成与第一种方法相同的工作。那么,为什么我们首选使用第一种方法呢?只是为了节省内存吗?
英文:
While studying pointer in C++, I encountered "Dynamic Memory allocation in arrays" which we execute like this :
int *array_ptr {std::nullptr};
size_t size{};
cout<<"Enter the size of the array: "<<endl;
cin>>size;
array_ptr = new int [size];
But my question is we can simply accomplish this by another method which is :
size_t size{};
cout<<"Enter the size of the array: "<<endl;
cin>>size;
int array [size] {};
The second method will do the same job as the first one. Then why do we use the first method in the first place? Is it just to save the memory?
答案1
得分: 8
以下是您要翻译的内容:
For many reasons
-
this is not a standard part of the c++ language (it has issues)
-
the data lives on the stack and so it has limited lifetime (it will disappear when the function its declared in finishes), plus stack space is limited (typically one meg or so)
-
what happens if you suddenly realize you need more entries? Maybe you cannot ask the user in advance how many entries they need
The best solution in c++ is to use std::vector
, this is dynamically growable, will automatically free its memory, plus it will do bounds checking for you either in debug builds (usually) or if you use at
instead or the []
operator.
My first "use std::vector
" today
英文:
For many reasons
-
this is not a standard part of the c++ language (it has issues)
-
the data lives on the stack and so it has limited lifetime (it will disappear when the function its declared in finishes), plus stack space is limited (typically one meg or so)
-
what happens if you suddenly realize you need more entries? Maybe you cannot ask the user in advance how many entries they need
The best solution in c++ is to use std::vector
, this is dynamically growable, will automatically free its memory, plus it will do bounds checking for you either in debug builds (usually) or if you use at
instead or the []
operator.
My first "use std::vector
" today
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论