通过引用-in C传递2d数组

时间:2018-04-24 06:42:54

标签: c arrays pass-by-reference

我正在编写一个接收2D阵列形式的3个方阵的函数。它也应该收到大小。当我编译时,我收到这样的错误! 请注意,我查看了互联网但无法找到解决方案

    #include <stdio.h>
    void matadd(int **a,int** b,int** c,int n){
    for (int i = 0; i < n; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            c[i][j] = a[i][j] + b[i][j];
        }
    }
    }
int main(){
    int x[4][4]= {
        {0,1,2,3},
        {4,5,6,7},
        {8,9,10,11},
        {12,13,14,15}
    };
    int y[4][4]= {
        {0,1,2,3},
        {4,5,6,7},
        {8,9,10,11},
        {12,13,14,15}
    };
    int z[4][4] = {0};

    matadd(&&x,&&y,&&z,4);
    for (int i = 0; i < 4; ++i)
    {
        for (int j = 0; j < 4; ++j)
        {
            printf("%d ", z[i][j]);
        }printf("\n");
    }
    return 0;
}

错误在于:

matadd.c: In function ‘main’:
matadd.c:26:9: warning: passing argument 1 of ‘matadd’ from incompatible pointer type [-Wincompatible-pointer-types]
  matadd(x,&&y,&&z,4);
         ^
matadd.c:2:6: note: expected ‘int **’ but argument is of type ‘int (*)[4]’
 void matadd(int **a,int** b,int** c,int n){
      ^~~~~~
matadd.c:26:2: error: label ‘z’ used but not defined
  matadd(x,&&y,&&z,4);
  ^~~~~~
matadd.c:26:2: error: label ‘y’ used but not defined

请注意不能硬编码数组的大小。不同的时间,可能会使用不同的尺寸!

1 个答案:

答案 0 :(得分:-1)

#include <stdio.h>
    void matadd(int a[4][4],int b[4][4],int c[4][4],int n){
    for (int i = 0; i < n; ++i)
    {
        for (int j = 0; j < n; ++j)
        {
            c[i][j] = a[i][j] + b[i][j];
        }
    }
    }
int main(){
    int x[4][4]= {
        {0,1,2,3},
        {4,5,6,7},
        {8,9,10,11},
        {12,13,14,15}
    };
    int y[4][4]= {
        {0,1,2,3},
        {4,5,6,7},
        {8,9,10,11},
        {12,13,14,15}
    };
    int z[4][4] = {0};

    matadd(x,y,z,4);

    for (int i = 0; i < 4; ++i)
    {
        for (int j = 0; j < 4; ++j)
        {
            printf("%d ", z[i][j]);
        }printf("\n");
    }

    return 0;
}