繁体   English   中英

我需要动态指定数组的大小

[英]I need to specify the size of an array dynamically

我有一个Nx3数组,需要将其作为函数进行填充(因此,vector不是一个选择)。 我已经知道N作为参数输入函数的大小。 我仍然收到“必须具有恒定值”的愚蠢错误,我的代码是:

double bspline_plot(double CP[], double Knot[], const int N, int d, int ncontrol, double *A){
    // CP are the control points
    //Knot is the knot vector
    //N is the number of internal point you want in each segment
    //d is the degree of the polynomials
    double min_x, max_x, dx;
    double *x_1;
    x_1 = new double[N];
    double A[N][2];
    int i, j, M, L;
    min_x = min(Knot);
    max_x = max(Knot);
    dx = (max_x - min_x) / N;
    for (i = 0; i <= N; i = i + 1)
    {
        x_1[i] = min_x + dx*i;
    }

    M = ncontrol;
    L = (sizeof(Knot) / sizeof(*Knot)); 
    if (L < d + M + 1) // This checks if the number of control points are positive
    {
        printf("Incorrectly defined knot vector\n");
        return;
    }
    else //This is the Cox - deBoor algorithm
    {
        for (i = 0; i <= N; i = i + 1)
        {
            for (j = 0; j <= L - 1; j = j + 1)
            {
                A[i][1] = A[i][1] + CP[j, 1] * CdB(j, d, x_1[i], Knot);
                A[i][2] = A[i][2] + CP[j, 2] * CdB(j, d, x_1[i], Knot);
                A[i][3] = A[i][3] + CP[j, 3] * CdB(j, d, x_1[i], Knot);
            }
            A[N][1] = CP[L, 2];
            A[N][2] = CP[L, 2];
            A[N][3] = CP[L, 1];
        }
    }
    return A;
}

我的另一个选择是输入一个数组,然后在函数中找到它的值,但这似乎有点愚蠢。

尝试通过以下方式使用std :: vector:

std::vector<std::vector<double>> A( N );
for( auto& row : A )
  row.resize( M );

要么

std::vector<std::vector<double>> A( N, std::vector<double>( M ));

通过快速检查,您的C ++代码中的问题似乎是以下数组声明:

double A[N][2];

您需要动态分配此2d数组,如下所示:

double** A = new double*[N];
for (int i=0; i<N; ++i)
    A[i] = new double[2];

看看这篇 SO文章以获得更多信息。

最后,我不得不将A分成三个向量,并将函数的输出从double更改为void,然后将(现在)三个向量读为double *。 然后,我可以只更改向量的内容,现在没有任何错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM