我们为什么在C++中使用动态内存分配来使用数组

huangapple go评论62阅读模式
英文:

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&lt;&lt;&quot;Enter the size of the array: &quot;&lt;&lt;endl;
cin&gt;&gt;size;
array_ptr = new int [size];

But my question is we can simply accomplish this by another method which is :

size_t size{};
cout&lt;&lt;&quot;Enter the size of the array: &quot;&lt;&lt;endl;
cin&gt;&gt;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

huangapple
  • 本文由 发表于 2023年3月7日 01:58:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654249.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定