简体   繁体   English

Static 和 C++ 中的动态 arrays 有什么区别?

[英]What is the difference between Static and Dynamic arrays in C++?

I have to do an assignment for my class and it says not to use Static arrays, only Dynamic arrays.我必须为我的 class 做一个作业,它说不使用 Static arrays,只有动态 ZA3CBC3F9D0B72F21C19CZE。 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.我以为 Static 是在编译时创建的,而 Dynamic 在运行时创建的,但我可能会将其误认为是 memory 分配。

Can you explain the difference between static array and dynamic array in C++?你能解释一下static数组和C++中的动态数组的区别吗?

Static 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 at compile time :它们在编译时必须具有固定的大小:

int foo[10];

Arrays created with operator new[] have dynamic storage duration and are stored on the heap (technically the "free store").使用operator new[]创建的数组具有动态存储持续时间并存储在堆上(技术上是“免费存储”)。 They can have any size during runtime , 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;

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. static 是 C 和 C++ 中的关键字,因此 static 在应用于变量或数组时具有非常特定的含义,而不是一般的描述性术语。 To compound the confusion, it has three distinct meanings within separate contexts.为了使混淆更加复杂,它在不同的上下文中具有三个不同的含义。 Because of this, a static array may be either fixed or dynamic.因此,静态数组可以是固定的也可以是动态的。

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.静态成员可能是初始化为 null 的指针,然后在第一次调用构造函数时分配。 (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, ie 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's)

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.动态数组在运行时使用“new”关键字(或 C 中的 malloc 系列)分配,并且它们的大小事先不知道。 dynamic allocations are not automatically cleaned up until the program stops running.在程序停止运行之前,不会自动清理动态分配。

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 variables are variables defined using static memory allocation .静态变量是使用静态内存分配定义的变量。 This is a general concept independent of C/C++.这是一个独立于 C/C++ 的一般概念。 In C/C++ we can create static variables with global, file, or local scope like this:在 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 w have in common is that the size for each of them is fixed and is defined at compile time.这些数组x, y, zw的共同点是它们每个的大小都是固定的,并且是在编译时定义的。

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 arrays which is impossible with stack-based storage.了解自动数组和静态数组之间的区别很重要的原因之一是静态存储通常在目标文件的数据部分(或BSS 部分)中实现,编译器可以使用绝对地址来访问数组这对于基于堆栈的存储是不可能的。

What's usually meant by a dynamic array is not one that is resizeable but one implemented using dynamic memory allocation with a fixed size determined at run-time.动态数组通常指的不是可调整大小的数组,而是使用动态内存分配实现的数组,其大小在运行时确定。 In C++ this is done using the new operator .在 C++ 中,这是使用new运算符完成的。

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::vector in C++ (or a variable length array in C ).对于真正的动态数组,应该使用 C++ 中的std::vector类的东西(或 C中的可变长度数组)。

What was meant for the assignment in the OP's question? OP 问题中的作业意味着什么? 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 new operator or a non-fixed sized array using eg std::vector .我认为很明显,想要的不是静态或自动数组,而是使用new运算符使用动态内存分配或使用例如std::vector的非固定大小数组的数组。

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::vector class from the C++ standard library will suffice.大多数时候,来自 C++ 标准库的std::vector类就足够了。 Use it like this:像这样使用它:

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

std::vector has operator[] defined, so you can use it with the same semantics as an array. std::vector定义了operator[] ,因此您可以使用与数组相同的语义来使用它。

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.

I think in this context it means it is static in the sense that the size is fixed.我认为在这种情况下,这意味着它是静态的,因为它的大小是固定的。 Use std::vector.使用 std::vector。 It has a resize() function.它有一个 resize() 函数。

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

Static Array :静态数组

  1. Static arrays are allocated memory at compile time.静态数组在编译时分配内存。
  2. Size is fixed.大小是固定的。
  3. Located in stack memory space.位于堆栈内存空间。
  4. Eg.例如。 : int array[10]; :整数数组[10]; //array of size 10 //大小为10的数组

Dynamic Array :动态数组:

  1. Memory is allocated at run time.内存是在运行时分配的。
  2. Size is not fixed.大小不固定。
  3. Located in Heap memory space.位于堆内存空间。
  4. Eg.例如。 : int* array = new int[10]; : int* 数组 = 新的 int[10];

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 框架中的垃圾收集器,否则存在内存泄漏的风险。

Static array :Efficiency.静态数组:效率。 No dynamic allocation or deallocation is required.不需要动态分配或释放。

Arrays declared in C, C++ in function including static modifier are static.在 C、C++ 中声明的数组在函数中包括静态修饰符是静态的。 Example: static int foo[5];示例:静态 int foo[5];

static array : The memory allocation is done at the complile time and the memory is allocated in the stack memory The size of the array is fixed. static array : The memory allocation is done at the complile time and the memory is allocated in the stack memory The size of the array is fixed.

dynamic array : The memory allocation is done at the runtime and the memory is allocated in the heap memory The size of the array is not fixed.动态数组:memory 分配在运行时完成,memory 分配在堆中 memory 数组的大小不固定。

Let's state this issue with a function让我们 state 这个问题用 function

if we have the static array then calling the function() will iterate all the fixed allocated components from the memory.如果我们有 static 数组,那么调用 function() 将从 memory 迭代所有固定分配的组件。 There will be no append.不会有 append。

On the other hand, a dynamic array will extend the memory if we append it.另一方面,如果我们使用 append,动态数组将扩展 memory。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM