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

查看:103
本文介绍了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.

我认为static是在编译时创建的,而dynamic是在运行时创建的,但是我可能会误以为是内存分配。

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天全站免登陆