繁体   English   中英

从C中的函数返回数组

[英]Returning an Array from a Function in C

我只是搞得一团糟。 我有一个函数应该采用一维数组,用其值进行一些计算,然后返回一个类似的数组与计算结果。 我不一定关心它是否返回相同的数组(使用新值),或者它是否在不同的内存位置创建一个新数组并返回它。 这就是我现在所拥有的。 这一切都有错误,但我不知道我做错了什么。 有人可以帮忙吗?

double s  = 10;
double b  = 2.6666;
double r  = 28;

double (*newVertex(double vtx[3] )) [] {

    static double newVtx[3];
    /*  Coordinates  */
    double x = vtx[0];
    double y = vtx[1];
    double z = vtx[2];

    double dt = 0.001;

    double dx = s*(y-x);
    double dy = x*(r-z)-y;
    double dz = x*y - b*z;
    newVtx[0] = x + dt*dx;
    newVtx[1] = y + dt*dy;
    newVtx[2] = z + dt*dz;

    return &newVtx;
}

int main(int argc, char *argv[]) {
    int i;

    /* Arrays to hold the coordinates */
    double thisPt[3] = {1, 1, 1};
    double nextPt[3];

    for (i=0;i<1000;i++) {
        printf("%5d %8.3f %8.3f %8.3f\n", i, thisPt[0], thisPt[1], thisPt[2]);
        nextPt = newVertex(&thisPt);
        thisPt = nextPt;
    }
    return 0;
} 

首先,您的函数声明看起来不必要地复杂。

如果您不打算创建一个新数组,那么它应该是这样的:

void function_name(double *parameter) {
    // code to change the parameter in place here    
}

或者,如果您想明确数组的长度(请参阅注释以获取更多信息):

#define ARRAY_SIZE 3
void function_name(double parameter[ARRAY_SIZE]) {
    // code to change the parameter in place here    
}

如果您打算创建一个新数组,那么您可以执行以下操作:

double * function_name(double *parameter) {
    double *result = (double *)malloc(sizeof(double * number_of_elements));
    // read parameter, write into result
    return result;
}

上面的代码片段假设number_of_elements是固定且已知的。 如果不是,那么您需要将它们作为附加参数处理。

接下来,这有几个原因:

double (*newVertex(double vtx[3] )) [] {    
    static double newVtx[3];
    // update newVtx    
    return &newVtx;
}

return语句返回局部变量的地址。 在这种特殊情况下,变量是静态的,因此一旦函数退出,变量就不会被覆盖。 但它首先真的需要保持静态吗? 它是静态的足够吗? 想想这样的代码:

double *v1 = newVertex(old_vertex);
double *v2 = newVertex(old_vertex);

您可能会认为可以单独处理这两个顶点,但它们指向内存中的完全相同的位置:静态变量的位置。 更常见的做法是动态地为数组分配空间(malloc,calloc)并返回指向已分配内存的指针。

这里nextPt = newVertex(&thisPt);

只是传递数组名称

newVertex(thisPt); //array name thispt==&thispt[0]        
thisPt = nextPt; //illegal and remove this line

你的功能

 void newVertex(double *); //declaration

 void newVertex(double *vtx) //defination
 {
 //donot return array 
 } 

函数调用后打印

 newVertex(thisPt); 
 printf("%5d %8.3f %8.3f %8.3f\n", i, thisPt[0], thisPt[1], thisPt[2]);

暂无
暂无

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

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