简体   繁体   中英

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

I'm trying to read from a 2D array I have declared in my main function but while being in a different function. I thought that if I will send a pointer to the first cell of that array then this will be possible, however I'm still having problem doing it

The issue is passing a 2d array which I have declared in my main function to another function, which itself is called from another function. I know this is a basic question but after many tries I still can't understand what I'm doing wrong and would sincerely appreciate your help.

I've simplified the following code the problem in the following code:

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;
   } 
  }
}

I have specefique the len of array in all of the function

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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