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

3
  • 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. Jul 23, 2013 at 15:12
  • 3
    See the diagram in this question: stackoverflow.com/a/11698458/1143274 Static arrays are not allocated on the stack or the heap. Dec 26, 2013 at 1:24
  • *fixed array vs dynamic array
    – csguy
    Sep 11, 2019 at 0:43

13 Answers 13

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;
15
  • 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, 2010 at 2:22
  • 27
    @Eddy: It depends on the situation as to whether a vector is necessary
    – Casebash
    Oct 14, 2010 at 2: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, 2010 at 0:27
  • 22
    @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. Oct 10, 2011 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. Feb 11, 2013 at 9:23
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.

9
  • 4
    +1, your answer is the most accurate and precise and should have received more votes.
    – Z boson
    Oct 17, 2014 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, 2016 at 22:17
  • "They are allocated before the main function runs." Why allocate the stack variables before the relevant block is entered? Sep 18, 2019 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. Sep 22, 2019 at 2: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? Sep 22, 2019 at 8:25
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.

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

3
  • 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, 2010 at 2: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. Apr 23, 2010 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, 2014 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.
1
  • 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, 2014 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.

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];
2
  • Not part of standard C++ (in C99 and as a compiler extension for gcc).
    – crashmstr
    Oct 20, 2014 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, 2022 at 0: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.

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

2
  • 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 stackoverflow.com/questions/17775066/…
    – Z boson
    Oct 17, 2014 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, 2014 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.

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.
    – YurkoFlisk
    Aug 5, 2022 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 5, 2022 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
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. Jan 10, 2015 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.