簡體   English   中英

將 ponter 從一個函數傳遞到另一個函數后讀取二維數組的問題

[英]problem reading 2d array after passing a ponter from one function to another

我試圖從我在主函數中聲明的二維數組中讀取,但同時在不同的函數中。 我認為如果我將向該數組的第一個單元格發送一個指針,那么這將是可能的,但是我仍然遇到問題

問題是將我在主函數中聲明的二維數組傳遞給另一個函數,該函數本身是從另一個函數調用的。 我知道這是一個基本問題,但經過多次嘗試,我仍然無法理解我做錯了什么,並真誠地感謝您的幫助。

我已將以下代碼簡化為以下代碼中的問題:

void main(){
N = 5, M = 4
double arr[][4] = {
    { 1,2,1,5 },
    { 8,9,7,2 },
    { 8,7,6,1 },
    { 5,4,5,3 },
    { 5,4,5,3 }
};

double(*pointer)[4];   // pointer creation
pointer = arr;         //assignation

function_1(pointer ,N,M);
}

function_1(double *arr, int N, int M){

  function_2(arr,N,M);
}
function_2(double *arr, int N, int M){
  
  int c = 0;
  
  for(int i=0; i<n; i++){
      for(int j=0l j<M; j++){
      arr[i][j] = c;          // error while trying to read from arr[i][j]
      c += 1;
   } 
  }
}

我在所有函數中都指定了數組的 len

function_2(double arr[5][4], int N, int M)
{
    int c = 0;
    for(int i=0; i<N; i++)
    {
        for(int j=0; j<M; j++)
        {
            arr[0][0] = c;
            c += 1;
        } 
    }
}

void function_1(double arr[5][4], int N, int M)
{
    function_2(arr,N,M);
}

int main()
{
    int N = 5, M = 4;
    double arr[][4] = 
    {
        { 1,2,1,5 },
        { 8,9,7,2 },
        { 8,7,6,1 },
        { 5,4,5,3 },
        { 5,4,5,3 }
    };
    function_1(arr ,N,M);
    return 0;
}

暫無
暫無

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

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