gpt4 book ai didi

c++ - 如果我只能创建一个数组,为什么还需要动态内存分配?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:29:43 25 4
gpt4 key购买 nike

<分区>

我正在阅读有关动态内存分配和静态内存分配的内容,发现以下有关动态内存分配的信息:

In the programs seen in previous chapters, all memory needs were determined before program execution by defining the variables needed. But there may be cases where the memory needs of a program can only be determined during runtime. For example, when the memory needed depends on user input.

所以我用C++写了下面的程序:

#include <iostream>

int main()
{
int n = 0;
int i = 0;

std::cout << "Enter size: ";
std::cin >> n;
int vector[n];

for (i=0; i<n; i++)
{
vector[i] = i;
}

return 0;
}

这个程序有效。我不明白它是如何工作的。这里的大小是什么时候确定的?在这种情况下如何分配 vector ?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com