Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The array is static, but the array size isn't know until runtime. How is this possible?

This has been troubling me for a while. It goes to the heart of my (lack of) understanding of the difference between static and dynamic memory allocation. The following array is an ordinary static array, which should mean the memory is allocated during compile time, correct? Yet, I've set it up so that the user enters the array size at runtime.

#include <iostream>
using namespace std;

int main() {
  cout << "how many elements should the array hold? ";
  int arraySize;
  cin >> arraySize;

  int arr[arraySize];

  for (int i = 0; i < arraySize; ++i)
    arr[i] = i * 2;

  return 0;
}

Note that there are no new or delete operators in this program. It works fine in Xcode 4.2 (default Clang compiler) as well as my school's UNIX server (GCC 4.4.5). How does the compiler know how much memory to allocate for arr when the array is created at compile time? Is this just a fluke of my compiler, dangerous code that could corrupt other memory, or is this legit?

like image 848
ryboe Avatar asked Jan 14 '12 09:01

ryboe


1 Answers

This is a non-standard extension of your C++ compilers. Note that in C, unlike in C++, this is officially supported (i.e. standard-mandated behaviour) since C99. In C++, it is not supported because there's already a solution to the problem: Use std::vector instead of the array.

Not however that the array is not using static memory allocation (nor dynamic memory allocation), but automatic memory allocation. Automatic variables are automatically deallocated at the end of the function (the memory area where they are allocated is known as the stack, because the allocations and deallocations on it have stack semantics). To have the array use static memory allocation you would have to put static in front of the definition (note that variables in global or namespace scope always use static memory allocation, though). However, if you make the variable static, you'll find that the compiler doesn't allow to use a non-constant array size any more.

Note that std::vector stores its data with dynamic memory allocations instead. For that reason, you can also use a non-constant size even for static std::vectors.

like image 76
celtschk Avatar answered Nov 03 '22 00:11

celtschk