简体   繁体   English

在C中返回2D数组的数组(指针)

[英]Returning array (pointer) of 2D array in C

A function dynamically creates an int array whose elements are predetermined to be int[2] . 函数动态创建一个int数组,其元素被预先确定为int[2] Is there any way to have a function assign values to that array and then return it to the caller. 有什么方法可以让函数将值分配给该数组,然后将其返回给调用方。

The below code accomplishes this task but throws warning: initialization from incompatible pointer type [enabled by default] 下面的代码完成了此任务,但发出警告: 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. 我知道可以动态分配两个维度的替代方法,但这是我很好奇的事情。

Rather than keep repeating the same clunky syntax it can be helpful to define a typedef in cases like this. 与像这样重复笨拙的语法一样,在这种情况下定义typedef可能会有所帮助。 This makes it easier to declare the correct return type for get_values : 这样可以更轻松地为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 现场演示

Recommended reading: Don't repeat yourself (DRY) . 推荐阅读: 不要重复自己(DRY)

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] ,这正是指针定义的样子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM