通过指针传递二维数组 [英] Passing two-dimensional array via pointer

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

问题描述

如何将 m 矩阵传递给 foo()?如果不允许我更改 foo() 的代码或原型?

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

推荐答案

如果你坚持上面foo的声明,即

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

那么让你的 foom 一起工作的唯一方法是创建一个额外的行索引"数组并传递它而不是 m>

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

没有办法将 m 直接传递给 foo.是不可能的.参数类型float ** 与参数类型float [4][4] 完全不兼容.

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].

此外,由于 C99 以上可以以更紧凑的方式表示为

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

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

附言如果仔细观察,您会发现这与 Carl Norum 在他的回答中所建议的基本相同.除了 Carl malloc-ing 数组内存,这不是绝对必要的.

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天全站免登陆