Search code examples
c++structdynamic-memory-allocation

Defining an array size with a variable in a structure


I have tried defining an array size with a variable in C++ before and although I do not fully understand the concept of dynamic memory, I made it work. However, I don't know how to do the same thing to the array 'point' in this case.

num=50;
struct pos
{
double x;
};

 struct pos point[num]; 

Is there anything obvious that I am overlooking?


Solution

  • These types of array sizes have to be compile time constants, so the compiler knows how much memory to reserve.

    int count = 50;
    int arr[count] // error!
    
    static const int count = 50;
    int arr[count]; // OK!
    

    The other option is dynamically allocated memory in which the size is known at run time.

    int count = 50;
    int* arr = new int[count];
    delete [] arr;
    

    However, generally you don't want to be dealing with raw pointers and memory allocation on your own, and should instead prefer:

    #include <vector>
    
    int count = 50;
    std::vector<int> arr(count);
    

    This will also work for any custom types you have provided they are copyable (hint: your example pos structure is copyable):

    #include <vector>
    
    int count = 50;
    std::vector<pos> arr(count);
    
    arr[0].x = 1;
    // ... etc
    arr[49].x = 49;
    

    std::vector has a rich interface, and all the details can be found here