簡體   English   中英

從C中的void函數返回2d數組

[英]Returning 2d array from void function in C

我有一個看起來像這樣的函數:

void swapRows(int row_1, int row_2, double **matrix, int n, int m)
{
   double arrTemp = (double *)malloc(m * sizeof(double));
   int i;   

   for(i = 0; i < m; i++)
   {
      arrTemp[i] = matrix[row_1][i];
      *matrix[row_1][i] = matrix[row_2][i];
   }

   for(i = 0; i < m; i++)
   {
    *matrix[row_2][i] = arrTemp[i];
   }

}

我嘗試使用兩顆星和一顆單星對數組進行解引用,但無法弄清楚。 我不想將其存儲在另一個數組中並通過double函數返回它,我需要從這個void函數中返回它。 我只是交換數組中的行,需要將修改后的數組返回給main函數。

只要您僅更改數組中的值,就無需執行任何特殊操作。 刪除函數中的所有*並訪問數組,就像您不想“返回”它一樣。

void swapRows(int row_1, int row_2, double **matrix, int n, int m){
    double arrTemp = (double *)malloc(m * sizeof(double));
    int i;  
    for(i = 0; i < m; i++){
        arrTemp[i] = matrix[row_1][i];
        matrix[row_1][i] = matrix[row_2][i]; //no *
    }
    for(i = 0; i < m; i++){
        matrix[row_2][i] = arrTemp[i]; //no *
    }
}

無關的問題,您在這里缺少此malloc的免費版本。
而且,正如WhozCraig指出的那樣,在double **matrix ,每行都是單獨分配的,您只需切換行指針即可。

void swapRows(int row_1, int row_2, double **matrix, int n, int m){
    double *tmp = matrix[row_1];
    matrix[row_1] = matrix[row_2];
    matrix[row_2] = tmp;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM