声明一个 C 函数以返回一个数组 [英] Declaring a C function to return an array

查看:33
本文介绍了声明一个 C 函数以返回一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个返回数组的函数?我试过这个

How can I make a function which returns an array? I tried this

const int WIDTH=11;
const int HEIGHT=11;

int main() {
  char A[WIDTH][HEIGHT];
  A=rand_grid(WIDTH,HEIGHT);
  return 0;
}

// Initializes a random board.
char[][] rand_grid(int i, int k) {
  char* A[i][k];
  for(j=0;j<i;++j) {
    for(l=0;l<k;++l) {
      A[j][l]=ran(10);
    }
  }
  return A;
}

// Returns a random number from the set {0,...,9}.
int ran(int i) {
  srand((unsigned int) time(0));
  return(rand()%10);
}

推荐答案

有几点需要指出.

首先,你不能像这里那样分配一个数组对象:

First of all, you cannot assign an array object as you do here:

char A[WIDTH][HEIGHT];  
A=rand_grid(WIDTH,HEIGHT);

数组类型的对象是不可修改的.

Objects of array type are not modifiable.

其次,C 中的函数不能返回数组类型.不过,它们可以将 指针 返回到数组:

Secondly, functions in C cannot return array types. They can return pointers to arrays, though:

char (*foo(int width))[HEIGHT]
{
  /**
   * dynamically allocate memory for a widthxHEIGHT array of char
   */
  char (*newArr)[HEIGHT] = malloc(sizeof *newArr * width);
  /**
   * initialize array contents here
   */
  return newArr;
}

语法有点混乱;它读作

       foo                                   -- foo
       foo(int width)                        -- is a function
                                             -- taking an int parameter
      *foo(int width)                        -- returning a pointer
     (*foo(int width))[HEIGHT]               -- to a HEIGHT-element array
char (*foo(int width))[HEIGHT]               -- of char

对于 C89,上述代码段中的 HEIGHT 必须是编译时常量整数表达式(宏、数字文字或由宏和/或数字文字组成的算术表达式).我不确定 C99 是否也是如此.

For C89, HEIGHT in the above snippet must be a compile-time constant integral expression (either a macro, a numeric literal, or an arithmetic expression consisting of macros and/or numeric literals). I'm not sure if that's also true for C99.

根据您发布的代码段,您要做的是获取已分配的数组并初始化其内容.请记住,在大多数情况下,数组类型的表达式将隐式转换为指向基类型的指针.IOW,如果你将一个 T 的 N 元素数组传递给一个函数,该函数实际接收的是一个指向 T 的指针:

Based on the snippet you've posted, what you want to do is to take an array you've already allocated and initialize its contents. Remember that in most contexts, an expression of an array type will implicitly be converted to a pointer to the base type. IOW, if you pass an N-element array of T to a function, what the function actually receives is a pointer to T:

void foo (T *p) {...}
...
T arr[N];
foo(arr);

对于二维数组,它有点丑:

For 2-d arrays, it's a little uglier:

void foo (T (*p)[M]) {...}
...
T arr[N][M];
foo(arr);

这也依赖于在编译时已知的 M,这限制了函数的有用性.您想要的是一个可以处理任意大小的二维数组的函数.我知道实现这一点的最好方法不是传递指向数组的指针,而是传递数组[1] 中第一个元素的地址,并将行数和列数作为单独的参数传递:

This also relies on M being known at compile time, which limits the function's usefulness. What you'd like is a function that can deal with a 2-d array of arbitrary size. The best way I know of to accomplish this is instead of passing a pointer to the array, pass the address of the first element in the array[1], and pass the number of rows and columns as separate parameters:

void foo(T *base, size_t rows, size_t cols) {...}
...
T arr[N][M];
foo (&arr[0][0], N, M);

所以你的 rand_grid 函数看起来像这样:

So your rand_grid function would look something like this:

void rand_grid(char *base, size_t rows, size_t cols)
{
  size_t i, j;
  for (i = 0; i < rows; i++)
  {
    for (j = 0; j < cols; j++)
    {
      /**
       * Since base is a simple char *, we must index it
       * as though it points to a 1-d array.  This works if
       * base points to the first element of a 2-d array,
       * since multi-dimensional arrays are contiguous.  
       */
      base[i*cols+j] = initial_value();
    }
  }
}

int main(void)
{
  char A[WIDTH][HEIGHT];
  rand_grid(&A[0][0], WIDTH, HEIGHT);
  ...
}

<小时>

  1. 即使表达式 &A[0][0]A 产生相同的值(A 的基地址),这两个表达式的类型是不同的.第一个表达式计算为指向 char 的简单指针 (char *),而第二个表达式计算为指向二维 char 数组的指针 (char (*)[HEIGHT]).
  1. Even though the expressions &A[0][0] and A yield the same value (the base address of A), the types of the two expressions are different. The first expression evaluates to a simple pointer to char (char *), while the second evaluates to a pointer to a 2-d array of char (char (*)[HEIGHT]).

这篇关于声明一个 C 函数以返回一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆