A function dynamically creates an int
array whose elements are predetermined to be int[2]
. Is there any way to have a function assign values to that array and then return it to the caller.
函数动态创建一个int数组,其元素预定为int [2]。有没有办法让函数为该数组赋值,然后将其返回给调用者。
The below code accomplishes this task but throws warning: initialization from incompatible pointer type [enabled by default]
以下代码完成此任务但引发警告:从不兼容的指针类型初始化[默认启用]
#include <stdlib.h>
#include <stdio.h>
int *get_values()
{
int (*x)[2] = malloc(sizeof(int[2])*3);
x[0][0] = 1;
x[0][1] = 2;
x[1][0] = 11;
x[1][1] = 12;
x[2][0] = 21;
x[2][1] = 22;
return x;
}
int main()
{
int (*x)[2] = get_values();
int i;
for (i=0; i!=3; i++)
printf("x[%d] = { %d, %d }\n", i, x[i][0], x[i][1]);
}
I'm aware of the alternative where you dynamically allocate both dimensions, but this is something that I am curious about.
我知道你动态分配两个维度的替代方案,但这是我很好奇的事情。
2 个解决方案
#1
6
Rather than keep repeating the same clunky syntax it can be helpful to define a typedef in cases like this. This makes it easier to declare the correct return type for get_values
:
而不是继续重复相同的笨重语法,在这种情况下定义typedef会很有帮助。这样可以更容易地为get_values声明正确的返回类型:
#include <stdlib.h>
#include <stdio.h>
typedef int I2[2];
I2 * get_values(void)
{
I2 * x = malloc(sizeof(I2) * 3);
x[0][0] = 1;
x[0][1] = 2;
x[1][0] = 11;
x[1][1] = 12;
x[2][0] = 21;
x[2][1] = 22;
return x;
}
int main()
{
I2 * x = get_values();
int i;
for (i=0; i!=3; i++)
printf("x[%d] = { %d, %d }\n", i, x[i][0], x[i][1]);
free(x);
}
现场演示
Recommended reading: Don't repeat yourself (DRY).
推荐阅读:不要重复自己(干)。
#2
3
And this is how it looks without a typedef:
这就是它没有typedef的样子:
int (*get_values(void))[2]
{
return NULL;
}
Pretty unreadable.
相当难以理解。
Notice in that function definition, if you replace get_values(void)
with x you get: int (*x)[2]
, which is exactly what the pointer definition looks like.
请注意,在该函数定义中,如果用x替换get_values(void),则得到:int(* x)[2],这正是指针定义的样子。
#1
6
Rather than keep repeating the same clunky syntax it can be helpful to define a typedef in cases like this. This makes it easier to declare the correct return type for get_values
:
而不是继续重复相同的笨重语法,在这种情况下定义typedef会很有帮助。这样可以更容易地为get_values声明正确的返回类型:
#include <stdlib.h>
#include <stdio.h>
typedef int I2[2];
I2 * get_values(void)
{
I2 * x = malloc(sizeof(I2) * 3);
x[0][0] = 1;
x[0][1] = 2;
x[1][0] = 11;
x[1][1] = 12;
x[2][0] = 21;
x[2][1] = 22;
return x;
}
int main()
{
I2 * x = get_values();
int i;
for (i=0; i!=3; i++)
printf("x[%d] = { %d, %d }\n", i, x[i][0], x[i][1]);
free(x);
}
现场演示
Recommended reading: Don't repeat yourself (DRY).
推荐阅读:不要重复自己(干)。
#2
3
And this is how it looks without a typedef:
这就是它没有typedef的样子:
int (*get_values(void))[2]
{
return NULL;
}
Pretty unreadable.
相当难以理解。
Notice in that function definition, if you replace get_values(void)
with x you get: int (*x)[2]
, which is exactly what the pointer definition looks like.
请注意,在该函数定义中,如果用x替换get_values(void),则得到:int(* x)[2],这正是指针定义的样子。