c - 如何在 C 函数中返回 int[N]*

标签 c

通过形参,我可以声明一个 int[N]* 类型的指针(在下面的代码中是 int (*A)[COL]) 。但我想知道如何将函数返回到这种类型的指针?

在我的代码中,int (*)[COL] 没有任何意义。

非常感谢你。

int (*)[COL] creat_2D_Array(int(*A)[COL], int ROW, int COL) {
    for (int i = 0; i < ROW; i++)
    {
        for (int j = 0; j < COL; j++)
        {
            A[i][j] = rand() % 20 + 1;
        }
    }
    return A;
}
//I add some code below after discussion with user3386109

//Or how can i return to a pointer of int[10]*
int (*)[10] creat_2D_Array(int(*A)[10]) {
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            A[i][j] = rand() % 20 + 1;
        }
    }
    return A;
}

最佳答案

语法类似于函数指针,但您只需使用 [...] 而不是 (...),例如:

type (*identifier)[size]

将函数名称和参数列表放入(* ... )中:

int (*creat_2D_Array(int (*A)[COL], int ROW, int COL_param))[COL] {
    for (int i = 0; i < ROW; i++)
    {
        for (int j = 0; j < COL; j++)
        {
            A[i][j] = rand() % 20 + 1;
        }
    }
    return A;
}

int (*creat_2D_Array_1(int(*A)[10]))[10] {
   for (int i = 0; i < 5; i++)
   {
       for (int j = 0; j < 10; j++)
       {
           A[i][j] = rand() % 20 + 1;
       }
   }
   return A;
}

第一个 creat_2D_Array 函数中的 COL 必须是常量表达式。

我有时使用 void* 指针从此类函数返回一个指向未知大小数组的指针,并在函数参数列表中组合简单的 VLA 声明,并期望调用者进行转换:

  void *creat_2D_Array(int ROW, int COL, int A[ROW][COL]) {
    for (int i = 0; i < ROW; i++)
    {
        for (int j = 0; j < COL; j++)
        {
            A[i][j] = rand() % 20 + 1;
        }
    }
    return A;
}

int main() {
   int input[5][6];
   int (*output)[6] = creat_2D_Array(5, 6, input);
   // remember these are pointers, you return the same pointer you inputted
   assert(input == output);
}

我发现这种方法很难维护。向某些模糊的对象或结构编写一些访问 API 和函数更容易使用(并允许断言和其他一些检查)。

关于c - 如何在 C 函数中返回 int[N]*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53664862/

相关文章:

我可以在主应用程序和多个线程中使用相同的套接字吗?

c - Win32 编辑控件 EM_SETSEL 不起作用

c - Windows 和 Linux 系统如何实现物理到虚拟 IRQ 映射?

c - 字符串复制基础

c++ - 在映射最小值和最大值时从无符号转换为有符号的最佳方法?

c - 浮点: how many matching significant figures?

c - 为什么 realloc() 会使我的程序崩溃?

iphone - Objective-C : How does 7 - 1 = 3?

c - 服务器-客户端线程接受错误/泄漏

c - 这个 sfrw(x,x_) 宏如何工作(msp430)?