C 函数的正确 return 类型?

correct return type for C function?

我在这样声明的函数中使用了一个字符串数组

char (*array)[PATH_MAX] = malloc (1000 * sizeof *array);

分配 1000 个大小为 PATH_MAX (1024) 的字符指针。

我希望函数 return 那个特定的数据结构,即 return 指针 array。但是我无法选择正确的 return 类型。

warning: returning 'char (*)[1024]' from a function with return type 'int' makes integer from pointer without a cast [-Wint-conversion]

我知道我不能将 int 作为 return 类型,但是 char** 也不起作用。

warning: returning 'char (*)[1024]' from a function with incompatible return type 'char **' [-Wincompatible-pointer-types]

我试过使用 char (*)[1024] 作为 return 类型,但它给了我一般的 C 错误消息,让我相信我没有使用正确的语法。

error: expected identifier or '(' before ')' token
   38 | char (*)[1024] read_dir (char *path) {
      |        ^

是否有实现此目的的正确语法,还是我只是做错了?

您需要定义函数如下:

char (*read_dir(char *path))[PATH_MAX] {

这将 return 类型指定为指向 char * 大小为 PATH_MAX 的数组的指针。

时间 typedef

typedef char arr1k_char[1000];

arr1k_char *foo(int n) {
    arr1k_char *x = malloc(n * sizeof *x);
    return x;
}

https://ideone.com/Cqxa61