簡體   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