数组的运行时分配(C++、FMX)

runtime allocation of array (C++, FMX)

我在运行时需要一个数组来保存一些 x-y 坐标数据。它可能从几十个点到几千个点不等。所以,为了提高效率,我想在运行时分配数组。我找到 an example 但我无法扩展它。这是我现在拥有的:

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;

此代码工作正常,但当我尝试更改为二维时,我得到 E2034 Cannot convert double( *)[2] to double*。这是我更改的导致错误的行:

A = new double[NumSamp][2];

我应该怎么做?我在 C++Builder (10.3.1) 中工作,目标是 Win32、iOS 和 Android.

在你的例子中,你首先忘记更新数组的类型。它不再是 double *,而是 double **。尽量将声明和初始化保持在同一行以避免这些问题。即 double **A = new double*[NumSamp];

此外,您不能像为二维数组那样分配动态内存。请尝试以下操作。

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

另外,第二个数组似乎是静态的。为什么不创建一个结构并使用向量,因为它们可以是动态的。例如

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