108

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++?

ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
user69514
  • 26,935
  • 59
  • 154
  • 188
  • 1
    Static is not the opposite of dynamic. Either the book you are using is terrible, or you are taking it out of context. I'm going to add a new answer below to hopefully clear this up. – Joshua Clayton Jul 23 '13 at 15:12
  • 3
    See the diagram in this question: http://stackoverflow.com/a/11698458/1143274 Static arrays are not allocated on the stack or the heap. – Evgeni Sergeev Dec 26 '13 at 01:24
  • *fixed array vs dynamic array – csguy Sep 11 '19 at 00:43

13 Answers13

121

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"). 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;
ivanleoncz
  • 9,070
  • 7
  • 57
  • 49
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
  • 21
    This is correct, but only to illustrate how it works. Please don't do this in real code but use a std::vector instead. – Eddy Pronk Apr 20 '10 at 02:22
  • 26
    @Eddy: It depends on the situation as to whether a vector is necessary – Casebash Oct 14 '10 at 02:07
  • 7
    @Casebash: In which situation would you prefer an array? "You should always prefer to use vectors or deques instead of arrays." - Herb Sutter (More exceptional C++) – Eddy Pronk Oct 15 '10 at 00:27
  • If you are fine with setting the maximum size at creation time, then you don't need a vector. Does actually occur occasionally. – Casebash Oct 15 '10 at 00:29
  • @Casebash: In that case there is no extra cost in using a vector either. – Eddy Pronk Oct 15 '10 at 03:11
  • 21
    @EddyPronk For memory fragmentation reasons one may use a fixed array as a sort of pool. Not every case demands the heap, there are special benefits to using stack based arrays. You're treating the std::vector as a golden hammer, a common anti-pattern. – void.pointer Oct 10 '11 at 19:16
  • 5
    @EddyPronk: I'm pretty sure Herb Sutter meant dynamic arrays, like `int* foo = new int[N]` which you have to `delete` yourself and hence be careful in presence of exception. Static arrays don't have these problems. – Alexander Malakhov Feb 11 '13 at 09:23
  • 2
    [Best practices](http://fredosaurus.com/notes-cpp/newdelete/50dynamalloc.html) suggest: Don't forget to reset the pointer `foo = NULL;` **after** `delete[] foo;`. Because in some systems, `delete` doesn't reset the pointer. – vulcan raven May 19 '13 at 22:00
  • @vulcanraven So in some systems, `delete` does actually reset the pointer? I didn't know, and always call `foo = NULL` after, unless it goes out of scope as in a destructor (I've always seen delete as a pass-by-value function, so has no access to `&foo`, and then can't set it to zero). – Boris Dalstein Jun 21 '13 at 04:59
  • When I think of a static array I think `static int foo[x]` and that's not allocated on the stack. – Z boson Oct 17 '14 at 09:20
  • Sloppy wording -> *Static arrays are created on the stack*. What does it refer to when it says "static array"? The differences between `static int a[5];` vs. `{ int a[5]; }` (local variable `a`) vs. `int a[5];`(global variable `a`) should be stated clearly. As such, this answer is incomplete and confusing. – P.P Oct 17 '14 at 14:25
  • Your edit is more accurate but less precise (the previous version was the other way around). You don't even use the word static now. The OP's question was "Can you explain the difference between static array and dynamic array in C++?". – Z boson Oct 17 '14 at 19:10
  • @Zboson Well, you've got to pick one or the other here. It seemed to me that the question was referring to this array distinction, and just used the wrong terminology. I used the same terminology when answering the question so it'd be understandable, but fixed it now because apparently 4 years later it's suddenly a problem. Feel free to edit it if it's confusing; it seems perfectly clear to me – Michael Mrozek Oct 17 '14 at 19:25
  • @MichaelMrozek you could explain that there are different kinds of static arrays (e.g. local and global) but anyway I'll either add my own answer or ask a question. – Z boson Oct 17 '14 at 19:29
  • [std::array](http://www.cplusplus.com/reference/array/array/) > std::vector for relatively small static-sized arrays – WaelJ Oct 20 '14 at 13:28
40

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.

Let me explain:

The first is C++ specific:

  • 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:

  • 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)

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.

Joshua Clayton
  • 1,669
  • 18
  • 29
  • 4
    +1, your answer is the most accurate and precise and should have received more votes. – Z boson Oct 17 '14 at 14:20
  • If you declare the size of the array with the `new[]` operator, how is it that the size isn't known until runtime? i.e. `int* p = new int[10]` – wulfgarpro Jun 21 '16 at 22:17
  • "They are allocated before the main function runs." Why allocate the stack variables before the relevant block is entered? – AlwaysLearning Sep 18 '19 at 14:44
  • Stack variables (generally local variables in a function)have a predefined size and position within a stack frame and the entire stack is allocated before the main function runs, @AlwaysLearning. When entering a stack frame via function call, the stack pointer is updated, but the new stack frame is within the stack. No more stack ever gets allocated. In fact, too big of variables (a giant array for instance) or too many function calls open at the same time results in a stack overflow, for which this site is named. – Joshua Clayton Sep 22 '19 at 02:13
  • @JoshuaClayton I think this cannot be correct. How can you allocate the stack frames (notice the plural) for a recursive function when you don't know how many times it will be entered? – AlwaysLearning Sep 22 '19 at 08:25
  • The stack frames are not individually allocated (i.e. memory is not requested from the OS for them). They are added to the stack, which has already been allocated when the process was instantiated. – Joshua Clayton Sep 24 '19 at 17:39
  • is it even correct to call fixed arrays, "static arrays"? – csguy Nov 19 '19 at 05:10
  • @csguy static is a keyword, which means fixed in the specific ways detailed above. const also means fixed in a different way. What do you mean by fixed? – Joshua Clayton Nov 19 '19 at 15:59
  • @JoshuaClayton oh i thought you were saying in your answer that static array means fixed array as opposed to a dynamic array, but youre saying that static arrays can be either dynamic or fixed/compile time correct? – csguy Nov 20 '19 at 05:25
13

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++. In C/C++ we can create static variables with global, file, or local scope like this:

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:

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.

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.

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.

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:

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).

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 new operator or a non-fixed sized array using e.g. std::vector.

Z boson
  • 32,619
  • 11
  • 123
  • 226
12

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. 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.

Ben Collins
  • 20,538
  • 18
  • 127
  • 187
  • 1
    I think it's fairly clear that by "dynamic array" they simply mean a dynamically allocated array (that is, one in which the size can be specified dynamically, at runtime). Like `new int[10]` – jalf Apr 20 '10 at 02:59
  • @jalf: I was more concerned about the term 'static'. I prefer to call a "dynamic array" an allocated or variable size array for the sake of consistency. – Ben Collins Apr 23 '10 at 14:58
  • Good point because a static array could be automatic and implemented on the stack or be global and implemented in a data section. Both are static but internally the code that accesses them can be very different. – Z boson Oct 17 '14 at 18:57
9

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.
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
Jagannath
  • 3,995
  • 26
  • 30
  • 6
    A global array is a static array and it's implemented in a data section and not from the stack. – Z boson Oct 17 '14 at 18:59
3

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.

Eddy Pronk
  • 6,527
  • 5
  • 33
  • 57
2

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];
Joshua Oliphant
  • 902
  • 3
  • 10
  • 17
  • Not part of standard C++ (in C99 and as a compiler extension for gcc). – crashmstr Oct 20 '14 at 13:54
  • 1
    Actually, this is a VLA (Variable-length Array), and as commented by @crashmstr, it's available at C99, and from C11 and on, is optional, and available thanks to extensions of GCC. VLAs is not a safe data structure in terms of compatibility, in my opinion. Even though it could work, I would avoid that. – ivanleoncz Jul 10 '22 at 00:09
2

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]; //array of size 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];
0

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.

Aadil Imran
  • 105
  • 1
  • 5
0

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

Khuê Phạm
  • 59
  • 1
  • 7
  • 1
    @admdrew, that's true but the question was never answered well. The best answer is Joshua Clayton's answer but I think a better answer is this one https://stackoverflow.com/questions/17775066/c-c-performance-of-static-arrays-vs-dynamic-arrays – Z boson Oct 17 '14 at 19:01
  • @Zboson Good to know, thanks. Heh and I just realized I made that comment almost a year ago now. – admdrew Oct 17 '14 at 19:20
0

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.

TEJA
  • 1
  • Stack-allocated arrays (and objects in general) are allocated/deallocated during *runtime*, but in a simple way - adding/subtracting a constant from the stack pointer, which is simpler then allocating/deallocating chunk of (pretty fragmented) heap memory for dynamically-allocated arrays. – YurkoFlisk Aug 05 '22 at 17:53
  • What can be in some sense said to be allocated 'in compile time' are static storage duration arrays (globals), because their storage is usually reserved during compile/link time within some section of executable file, so as soon as program image is loaded for execution into RAM, this storage is already present in program's address space. – YurkoFlisk Aug 05 '22 at 17:54
0

Let's state this issue with a function

if we have the static array then calling the function() will iterate all the fixed allocated components from the memory. There will be no append.

On the other hand, a dynamic array will extend the memory if we append it.

-4

static arrary meens with giving on elements in side the array

dynamic arrary meens without giving on elements in side the array

example:

     char a[10]; //static array
       char a[];  //dynamic array
  • I think he said correct. When you an exact length to array it's a static array and when you don't give length it's a dynamic array. but as he don't know how to write English that's why people marking down this answer. – muhammad tayyab Jan 10 '15 at 19:24