C++ 中的静态数组与动态数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2672085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 00:17:30  来源:igfitidea点击:

Static array vs. dynamic array in C++

c++dynamicarraysstaticallocation

提问by user69514

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

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.

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

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

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

回答by Michael Mrozek

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];

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:

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

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

回答by Joshua Clayton

static is a keyword in C and C++, so rather than a general descriptive term, static has very specific meaning when applied to a variable or array. To compound the confusion, it has three distinct meanings within separate contexts. Because of this, a static array may be either fixed or dynamic.

static 是 C 和 C++ 中的关键字,因此在应用于变量或数组时,static 不是一般的描述性术语,而是具有非常具体的含义。更令人困惑的是,它在不同的上下文中具有三种不同的含义。因此,静态数组可以是固定的,也可以是动态的。

Let me explain:

让我解释:

The first is C++ specific:

第一个是 C++ 特定的:

  • A static class member is a value that is not instantiated with the constructor or deleted with the destructor. This means the member has to be initialized and maintained some other way. static member may be pointers initialized to null and then allocated the first time a constructor is called. (Yes, that would be static and dynamic)
  • 静态类成员是一个不使用构造函数实例化或不使用析构函数删除的值。这意味着必须以其他方式初始化和维护成员。静态成员可以是初始化为空的指针,然后在第一次调用构造函数时分配。(是的,那将是静态和动态的)

Two are inherited from C:

两个是从 C 继承的:

  • within a function, a static variable is one whose memory location is preserved between function calls. It is static in that it is initialized only once and retains its value between function calls (use of statics makes a function non-reentrant, i.e. not threadsafe)

  • static variables declared outside of functions are global variables that can only be accessed from within the same module (source code file with any other #include's)

  • 在函数中,静态变量是在函数调用之间保留其内存位置的变量。它是静态的,因为它只初始化一次并在函数调用之间保留其值(使用静态使函数不可重入,即不是线程安全的)

  • 在函数外部声明的静态变量是全局变量,只能从同一模块内访问(源代码文件与任何其他 #include)

The question (I think) you meant to ask is what the difference between dynamic arrays and fixed or compile-time arrays. That is an easier question, compile-time arrays are determined in advance (when the program is compiled) and are part of a functions stack frame. They are allocated before the main function runs. dynamic arrays are allocated at runtime with the "new" keyword (or the malloc family from C) and their size is not known in advance. dynamic allocations are not automatically cleaned up until the program stops running.

您想问的问题(我认为)是动态数组与固定或编译时数组之间的区别。这是一个更简单的问题,编译时数组是预先确定的(在编译程序时)并且是函数堆栈帧的一部分。它们在 main 函数运行之前分配。动态数组在运行时使用“new”关键字(或 C 中的 malloc 系列)分配,并且它们的大小事先未知。在程序停止运行之前,不会自动清除动态分配。

回答by Ben Collins

I think the semantics being used in your class are confusing. What's probably meant by 'static' is simply "constant size", and what's probably meant by "dynamic" is "variable size". In that case then, a constant size array might look like this:

我认为您班级中使用的语义令人困惑。“静态”可能意味着“恒定大小”,而“动态”可能意味着“可变大小”。在这种情况下,常量大小的数组可能如下所示:

int x[10];

and a "dynamic" one would just be any kind of structure that allows for the underlying storage to be increased or decreased at runtime. Most of the time, the std::vectorclass from the C++ standard library will suffice. Use it like this:

而“动态”的只是允许在运行时增加或减少底层存储的任何类型的结构。大多数情况下,std::vector来自 C++ 标准库的类就足够了。像这样使用它:

std::vector<int> x(10); // this starts with 10 elements, but the vector can be resized.

std::vectorhas operator[]defined, so you can use it with the same semantics as an array.

std::vectoroperator[]定义,因此您可以使用与数组相同的语义来使用它。

回答by Jagannath

Static arrays are allocated memory at compile time and the memory is allocated on the stack. Whereas, the dynamic arrays are allocated memory at the runtime and the memory is allocated from heap.

静态数组在编译时分配内存,内存分配在堆栈上。而动态数组在运行时分配内存,内存从堆分配。

int arr[] = { 1, 3, 4 }; // static integer array.   
int* arr = new int[3]; // dynamic integer array.

回答by Z boson

It's important to have clear definitions of what terms mean. Unfortunately there appears to be multiple definitions of what static and dynamic arrays mean.

对术语的含义有明确的定义很重要。不幸的是,静态和动态数组的含义似乎有多种定义。

Static variablesare variables defined using static memory allocation. This is a general concept independent of C/C++. In C/C++ we can create static variables with global, file, or local scope like this:

静态变量是使用静态内存分配定义的变量。这是一个独立于 C/C++ 的一般概念。在 C/C++ 中,我们可以创建具有全局、文件或局部作用域的静态变量,如下所示:

int x[10]; //static array with global scope
static int y[10]; //static array with file scope
foo() {
    static int z[10]; //static array with local scope

Automatic variables are usually implemented using stack-based memory allocation. An automatic array can be created in C/C++ like this:

自动变量通常使用基于堆栈的内存分配来实现。可以在 C/C++ 中创建一个自动数组,如下所示:

foo() {
    int w[10]; //automatic array

What these arrays , x, y, z, and whave in common is that the size for each of them is fixed and is defined at compile time.

这些数组、x, y, z、 和w的共同点是每个数组的大小都是固定的,并且是在编译时定义的。

One of the reasons that it's important to understand the distinction between an automatic array and a static array is that static storage is usually implemented in the data section(or BSS section) of an object file and the compiler can use absolute addresses to access the arrayswhich is impossible with stack-based storage.

理解自动数组和静态数组之间的区别很重要的原因之一是静态存储通常在目标文件的数据段(或BSS 段)中实现,编译器可以使用绝对地址来访问数组这对于基于堆栈的存储是不可能的。

What's usually meant by a dynamic arrayis not one that is resizeable but one implemented using dynamic memory allocationwith a fixed size determined at run-time. In C++ this is done using the newoperator.

动态数组通常意味着不是可调整大小的数组,而是使用动态内存分配实现的数组,其大小在运行时确定。在 C++ 中,这是使用newoperator完成的。

foo() {
   int *d = new int[n]; //dynamically allocated array with size n     

But it's possible to create an automatic array with a fixes size defined at runtime using alloca:

但是可以使用在运行时定义的修复大小创建一个自动数组alloca

foo() {
    int *s = (int*)alloca(n*sizeof(int))

For a true dynamic array one should use something like std::vectorin C++ (or a variable length array in C).

对于真正的动态数组,应该使用类似于std::vectorC++ 的东西(或 C 中的可变长度数组)。

What was meant for the assignment in the OP's question? I think it's clear that what was wanted was not a static or automatic array but one that either used dynamic memory allocation using the newoperator or a non-fixed sized array using e.g. std::vector.

OP问题中的任务是什么意思?我认为很明显,我们想要的不是静态或自动数组,而是使用new运算符使用动态内存分配或使用例如std::vector.

回答by Eddy Pronk

I think in this context it means it is static in the sense that the size is fixed. Use std::vector. It has a resize() function.

我认为在这种情况下,这意味着它是静态的,因为大小是固定的。使用 std::vector。它有一个 resize() 函数。

回答by Joshua Oliphant

You could have a pseudo dynamic array where the size is set by the user at runtime, but then is fixed after that.

您可以拥有一个伪动态数组,其中的大小由用户在运行时设置,然后在此之后固定。

int size;
cin >> size;
int dynamicArray[size];

回答by Aadil Imran

Yes right the static array is created at the compile time where as the dynamic array is created on the run time. Where as the difference as far is concerned with their memory locations the static are located on the stack and the dynamic are created on the heap. Everything which gets located on heap needs the memory management until and unless garbage collector as in the case of .net framework is present otherwise there is a risk of memory leak.

是的,静态数组是在编译时创建的,而动态数组是在运行时创建的。就其内存位置而言,区别在于静态位于堆栈上,而动态位于堆上。位于堆上的所有内容都需要内存管理,除非存在 .net 框架中的垃圾收集器,否则存在内存泄漏的风险。

回答by Khuê Ph?m

Static array :Efficiency. No dynamic allocation or deallocation is required.

静态数组:效率。不需要动态分配或解除分配。

Arrays declared in C, C++ in function including static modifier are static. Example: static int foo[5];

在 C、C++ 中声明的数组包括静态修饰符是静态的。示例:静态 int foo[5];

回答by karthik

static arrary meens with giving on elements in side the array

静态数组表示数组中的元素

dynamic arrary meens without giving on elements in side the array

动态数组 meens 不放弃数组中的元素

example:

例子:

     char a[10]; //static array
       char a[];  //dynamic array