通过指针传递的二维阵列 [英] Passing two-dimensional array via pointer

查看:92
本文介绍了通过指针传递的二维阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何通过并购矩阵为foo()?如果我不能改变code或foo的原型()?

 无效美孚(浮动**时)
{
    INT I,J;
    对于(I = 0; I&下; 4;我+ +)
        为(J = 0; J&下; 4; J ++)
            的printf(%F \\ N,点[I] [J]);}诠释的main()
{
    浮米[4] [4];    INT I,J;
    对于(I = 0; I&下; 4;我+ +)
        为(J = 0; J&下; 4; J ++)
            M [] [J] = I + J;    美孚(??? ???米);
}


解决方案

如果你坚持上述声明,即

 无效美孚(浮动**时)

和使用内置的2D阵列,即

 浮动米[4] [4];

然后做的唯一途径你的 M 工作是创建一个额外的行索引数组并通过它来代替 M

  ...
浮* m_rows [4] = {M [0],M [1],M [2],M [3]};
富(m_rows);

有没有办法 M 传递给直接。是不可能的。参数类型浮法** 与参数类型不兼容绝望浮法[4] [4]

另外,由于C99以上可以以更紧凑的方式pssed前$ P $如

 美孚((浮动* []){M [0],M [1],M [2],M [3]});

P.S。如果你仔细看,你会认为这是基本上是同样的事情,什么卡尔Norum时他的回答提出。除卡尔的malloc -ing数组的内存,这完全没有必要的。

How do I pass the m matrix to foo()? if I am not allowed to change the code or the prototype of foo()?

void foo(float **pm)
{
    int i,j;
    for (i = 0; i < 4; i++)
        for (j = 0; j < 4; j++)
            printf("%f\n", pm[i][j]);

}

int main ()
{
    float m[4][4];

    int i,j;
    for (i = 0; i < 4; i++)
        for (j = 0; j < 4; j++)
            m[i][j] = i+j;

    foo(???m???);
}

解决方案

If you insist on the above declaration of foo, i.e.

void foo(float **pm)

and on using a built-in 2D array, i.e.

float m[4][4];

then the only way to make your foo work with m is to create an extra "row index" array and pass it instead of m

...
float *m_rows[4] = { m[0], m[1], m[2], m[3] };
foo(m_rows);

There no way to pass m to foo directly. It is impossible. The parameter type float ** is hopelessly incompatible with the argument type float [4][4].

Also, since C99 the above can be expressed in a more compact fashion as

foo((float *[]) { m[0], m[1], m[2], m[3] });

P.S. If you look carefully, you'll that this is basically the same thing as what Carl Norum suggested in his answer. Except that Carl is malloc-ing the array memory, which is not absolutely necessary.

这篇关于通过指针传递的二维阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆