是否可以返回(* ptr)[2]类型?

时间:2015-03-23 22:51:10

标签: c matrix malloc

如果没有,我如何使用*ptr表示?这似乎逃避了我......

基本上我想返回N by 2矩阵,我希望它在内存中保持一致。

1 个答案:

答案 0 :(得分:6)

typedef是你的朋友:

typedef int A[2]; // typedef an array of 2 ints

A *foo(int n)
{
    A *a = malloc(n * sizeof(A));   // malloc N x 2 array

    // ... do stuff to initialise a ...

    return a;                       // return it
}

要了解typedef有用的原因,请考虑没有typedef的等效实现(感谢@JohnBode为此示例提供了正确的语法):

int (*foo(int n))[2]
{
    int (*a)[2] = malloc(n * sizeof *a);   // malloc N x 2 array

    // ... do stuff to initialise a ...

    return a;                              // return it
}

<小时/> 请注意,cdecl是编码和解码神秘C声明的有用工具 - 在cdecl.org甚至还有一个方便的在线版本。

相关问题