静态内存分配与动态内存分配类似
代码:
int r, c;
cin >> r >> c;
int matrix[r][c];
我不明白运行时分配背后的想法。目的是在运行时分配内存,但在上面的代码部分中我们正在做同样的事情。
当这部分代码运行时,输入大小在运行时给出,矩阵根据行和列的大小分配内存,那么它是如何静态或编译时分配的呢?
Code:
int r, c;
cin >> r >> c;
int matrix[r][c];
I don't understand the idea behind runtime allocation. The aim is to allocate memory during runtime but in the above section of code we are doing the same.
When this part of code is run, the inputs sizes are given during runtime and matrix is allocated memory according to the size of rows and columns, so how is it static or compile time allocation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该声明
是可变长度数组的声明。
该数组具有自动存储期限。当变量
r
和c
的值已知时,该数组是在运行时创建的。然而,可变长度数组并不是标准的 C++ 功能。
您可以使用标准容器 std::vector 代替数组,例如
在这种情况下,矩阵的所有元素都将被零初始化。
This declaration
is a declaration of a variable length array.
This array has automatic storage duration. And the array is created at run-time when the values of the variables
r
andc
will be known.However variable length arrays are not a standard C++ feature.
Instead of the array you could use the standard container std::vector like
In this case all elements of the matrix will be zero-initialized.
静态但在运行时分配。
静态分配是固定大小的,发生在快速但小的堆栈上:
动态分配可以动态调整大小,但不能在堆上分配小东西:
只有动态内存可以传递到不同的作用域,但需要删除完成后就可以了。
Static but allocated at runtime.
Static allocation is fixed size and occurrs on the fast but small stack:
Dynamic allocation can be dynamically sized but it is not performat to allocate small thing on the heap:
Only dynamic memory can be passed to different scopes but you need to
delete
it when you're done.