gpt4 book ai didi

c - 在 C 中返回二维数组的数组(指针)

转载 作者:太空宇宙 更新时间:2023-11-04 05:12:28 24 4
gpt4 key购买 nike

函数动态创建一个 int 数组,其元素预先确定为 int[2]。有什么方法可以让函数为该数组赋值,然后将其返回给调用者。

下面的代码完成了这个任务但是抛出警告: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]);
}

我知道动态分配两个维度的替代方案,但我对此感到好奇。

最佳答案

与其不断重复相同的笨拙语法,不如在这种情况下定义一个 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);
}

LIVE DEMO

推荐阅读:Don't repeat yourself (DRY) .

关于c - 在 C 中返回二维数组的数组(指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36450009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com