Search code examples
firemonkeyc++builder

runtime allocation of array (C++, FMX)


i need an array at runtime to hold some x-y coordinate data. It may be anywhere from a few dozen points to several thousands. So, to be efficient i'd like to allocate the array at runtime. I found an example but i can't extend it. Here is what i have now:

double *A;
A = new double[NumSamp];  // NumSamp is an int set in earlier code at runtime
for (int y = 1; y < NumSamp ; y++) {
       A[y] = y;
}
delete [] A;
A = NULL;

This code works fine, but when i try to change to two dimensions i get E2034 Cannot convert double( *)[2] to double*. Here is the line i changed that caused the error:

A = new double[NumSamp][2];

How should i be doing this? I'm working in C++Builder (10.3.1) and will target Win32, iOS, and Android.


Solution

  • In your example, you firstly forgot to update the type of the array. It is no longer double * but actually double **. Try to keep the declare and the initialization on the same line to avoid these problems. i.e. double **A = new double*[NumSamp];

    Also, you can't allocate dynamic memory like that for a 2d array. Try the following.

    int main()
    {
        int const Y_VAL = 1;
        int const X_VAL = 0;
        // declare array as a 2d array
        double **A;
        // Allocate memory for main array
        A = new double*[NumSamp]; 
        // allocate memory for each sub array
        for (int y = 0; y < NumSamp ; y++) {
           A[y] = new double[2];
        }
    
        for ( int y = 0; y < NumSamp; ++y) {
            A[y][Y_VAL] = 4; // Initialize X and Y values
            A[y][X_VAL] = 4;
        }    
    
    
    
        // free memory
        for (int y = 0; y < NumSamp ; y++) {
            delete[] A[y];
        }
        delete [] A;
        A = NULL;
    }
    

    Also, the second array seems to be static. Why not just create a struct and use vector since they are can be dynamic. e.g.

    struct Data
    {
        double x, y;
        // Constructor with initializer list to initialize data members x and y
        Data( double const _x, double const _y ) : x(_x), y(_y){}
    };
    
    int main()
    {
        std::vector<Data> A;
        A.reserve(NumSamp); // reserve memory so it does not need to resize the capacity
        for(auto a : A)
        {
             a.emplace_back( 2, 5 ); // Initialize all "Data" with x=2, y=5;
        }
        // access data
        for(auto a : A)
        {
            std::cout << a.x << ":" << a.y << '\n';
        }
        std::cout << std::endl;
    }