可以输入 return (*ptr)[2] 吗?
Is it possible to return (*ptr)[2] type?
如果不是,我如何使用 *ptr
来表示它?这似乎在逃避我...
基本上我想要 return N by 2
矩阵并且我希望它在内存中保持一致。
typedef
s 是你的朋友:
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 is a useful tool for encoding and decoding cryptic C declarations - there's even a handy online version at cdecl.org.
如果不是,我如何使用 *ptr
来表示它?这似乎在逃避我...
基本上我想要 return N by 2
矩阵并且我希望它在内存中保持一致。
typedef
s 是你的朋友:
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 is a useful tool for encoding and decoding cryptic C declarations - there's even a handy online version at cdecl.org.