Search code examples
c++arraysc++11typedef

I tried to define a dynamically growing array using typedef and it works up to 79 index, beyond that it doesnt, can someone sort this out?


Without giving an explicit size, it works up to index 79. It prints the value 200 at index 79, but when I increase the index by 1 that is 80, it prints nothing and program terminates.

#include <iostream>
using namespace std;

typedef int list[];
int main() {
   list myList{};
   myList[79]={200};
   cout<<myList[79]; // OUTPUT: 200
   return 0;
}
#include <iostream>
using namespace std;

typedef int list[];
int main() {
   list myList{};
   myList[80]={200};
   cout<<myList[80]; // No Output and Process finished with exit code -1073741819 (0xC0000005)
   return 0;
}

Solution

  • First, try to do the following:

    list myList {};
    cout << sizeof(myList) << endl;
    // Prints 0, since no elements 
    // Note, the number does not signifies the number of elements,
    // it signifies the number of bytes.
    

    The int foo[] is not a dynamically growing array, it is legacy of C and is as primitive as it can be. When you subscript an array, it does not add an element at the index (nor up to the index).

    When you do the myList[79]={200}; it does not creates an element, and especially does not populates the array up to this index. Here, your program just tries to access an out of bound memory location (and does write to it, which may be the worst part of it all). It does not matter whether it is 79 or 80, either will lead to undefined behavior.

    Note, the T foo[] arrays have no convince for their user or any internal intelligence in them, they represent raw memory. There's no bounds checking, no implicit or explicit growing of the allocated memory.

    It is up to the programmer that uses this type to ensure that subscript value is in the allowed range (up to the predetermined size of the array).

    That's why C++ programmers should use any appropriate Standard Library container for any real world applications.