2D array passing to a function

后端 未结 2 1499
梦如初夏
梦如初夏 2021-01-21 05:09

I\'ve been reading this question but I\'m not able to get the resulting code to solve the problem. How should I change this in order to make it work?

void print         


        
相关标签:
2条回答
  • 2021-01-21 05:44

    You are passing in a pointer to an array, but your function is expecting a pointer to a pointer. In C, the array name decays to a value that is the pointer to the first array element. In this case, the first array element is an array, so the function argument decays to a pointer to an array.

    Here is one way you can fix this. Change the function to take a void * so that the dimension does not interfere with the argument. Then the dimension argument is used in the function body to create the proper pointer type for the 2D array.

    void print2(void *p,int n,int m)
    {
        int i,j;
        int (*array)[m] = p;
        for(i=0;i<n;i++)
        {
           for(j=0;j<m;j++)
              printf("%d ",array[i][j]);
           printf("\n");
        }
    }
    

    If you are willing to change the order of the arguments, then you can use the proper type for the array argument:

    void print2(int n, int m, int array[n][m])
    {
        int i,j;
        for(i=0;i<n;i++)
        {
           for(j=0;j<m;j++)
              printf("%d ",array[i][j]);
           printf("\n");
        }
    }
    

    Since Jack asked about C89, here's a way to handle it. Since a 2D array is organized the same as a long 1D array in memory, you can just walk the passed in pointer as such. Again, we accept the input parameter as a void * to avoid dealing with the decayed type. Then, we treat the pointer as a long 1D array, but we walk it according to the proper dimensions:

    void print2(void *p, int n, int m)
    {
        int i,j;
        int *array = p;
        for(i=0;i<n;i++)
        {
           for(j=0;j<m;j++)
              printf("%d ",array[i*m+j]);
           printf("\n");
        }
    }
    
    0 讨论(0)
  • 2021-01-21 05:50

    In your question you are passing arguments as pointer to an array. Do as given below :

    void print2(int (*array)[4],int n,int m)
    {
        int i,j;
        for(i=0;i<n;i++)
        {
           for(j=0;j<m;j++)
           printf("%d ",array[i][j]);
    
           printf("\n");
        }
    }
    
    0 讨论(0)
提交回复
热议问题