C++ 中的静态数组与动态数组 [英] Static array vs. dynamic array in C++

查看:79
本文介绍了C++ 中的静态数组与动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++ 中的静态数组和动态数组有什么区别?

What is the difference between a static array and a dynamic array in C++?

我必须为我的班级做一个作业,它说不要使用静态数组,只能使用动态数组.我在书上和网上看过,但我似乎不明白.

I have to do an assignment for my class and it says not to use static arrays, only dynamic arrays. I've looked in the book and online, but I don't seem to understand.

我认为静态是在编译时创建的,而动态是在运行时创建的,但我可能将其误认为是内存分配.

I thought static was created at compile time and dynamic at runtime, but I might be mistaking this with memory allocation.

你能解释一下 C++ 中静态数组和动态数组的区别吗?

Can you explain the difference between static array and dynamic array in C++?

推荐答案

局部数组是在栈上创建的,并且有自动存储时长——你不需要手动管理内存,但是当函数调用它们时它们就会被销毁结束了.它们必须具有固定大小:

Local arrays are created on the stack, and have automatic storage duration -- you don't need to manually manage memory, but they get destroyed when the function they're in ends. They necessarily have a fixed size:

int foo[10];

使用operator new[] 创建的数组具有动态存储持续时间并存储在堆上(技术上为自由存储").它们可以有任何大小,但您需要自己分配和释放它们,因为它们不是堆栈帧的一部分:

Arrays created with operator new[] have dynamic storage duration and are stored on the heap (technically the "free store"). They can have any size, but you need to allocate and free them yourself since they're not part of the stack frame:

int* foo = new int[10];
delete[] foo;

这篇关于C++ 中的静态数组与动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆