What is the difference between Static and Dynamic arrays in C++?
Asked Answered
P

13

109

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

Perutz answered 20/4, 2010 at 2:3 Comment(3)
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.Versicolor
See the diagram in this question: https://mcmap.net/q/17458/-where-are-static-variables-stored-in-c-and-c Static arrays are not allocated on the stack or the heap.Serrano
*fixed array vs dynamic arrayLingenfelter
P
125

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;
Peta answered 20/4, 2010 at 2:8 Comment(15)
This is correct, but only to illustrate how it works. Please don't do this in real code but use a std::vector instead.Autarky
@Eddy: It depends on the situation as to whether a vector is necessaryJoelie
@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++)Autarky
If you are fine with setting the maximum size at creation time, then you don't need a vector. Does actually occur occasionally.Joelie
@Casebash: In that case there is no extra cost in using a vector either.Autarky
@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.Tuber
@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.Subarctic
Best practices suggest: Don't forget to reset the pointer foo = NULL; after delete[] foo;. Because in some systems, delete doesn't reset the pointer.Lm
@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).Australorp
When I think of a static array I think static int foo[x] and that's not allocated on the stack.Predictory
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.Schlosser
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++?".Predictory
@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 mePeta
@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.Predictory
std::array > std::vector for relatively small static-sized arraysDado
V
41

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.

Versicolor answered 23/7, 2013 at 15:30 Comment(9)
+1, your answer is the most accurate and precise and should have received more votes.Predictory
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]Scandian
"They are allocated before the main function runs." Why allocate the stack variables before the relevant block is entered?Brenan
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.Versicolor
@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?Brenan
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.Versicolor
is it even correct to call fixed arrays, "static arrays"?Lingenfelter
@Lingenfelter 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?Versicolor
@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?Lingenfelter
P
14

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.

Predictory answered 20/10, 2014 at 13:15 Comment(0)
H
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.

Hereafter answered 20/4, 2010 at 2:11 Comment(3)
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]Valence
@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.Hereafter
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.Predictory
F
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.
Fatherhood answered 20/4, 2010 at 2:8 Comment(1)
A global array is a static array and it's implemented in a data section and not from the stack.Predictory
A
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.

Autarky answered 20/4, 2010 at 2:6 Comment(0)
M
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];
Monjo answered 17/10, 2014 at 3:55 Comment(2)
Not part of standard C++ (in C99 and as a compiler extension for gcc).Sumerian
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.Sudden
B
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];
Brace answered 15/9, 2020 at 11:21 Comment(0)
S
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.

Snavely answered 27/2, 2013 at 7:43 Comment(0)
N
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];

Notum answered 17/12, 2013 at 13:44 Comment(2)
@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 #17775566Predictory
@Zboson Good to know, thanks. Heh and I just realized I made that comment almost a year ago now.Welldressed
E
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.

Engird answered 4/8, 2022 at 0:8 Comment(2)
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.Agitato
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.Agitato
E
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.

Elfredaelfrida answered 19/9, 2022 at 9:40 Comment(0)
S
-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
Sightly answered 27/2, 2013 at 6:46 Comment(1)
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.Sunnysunproof

© 2022 - 2024 — McMap. All rights reserved.