简体   繁体   English

如何指定指向void的指针数组的返回类型?

[英]How do I specifiy the return type for an array of pointers to void?

I want to return an array of pointers to void . 我想返回一个指向void的指针数组。 How do I specify this in the function prototype? 如何在函数原型中指定?

int*[] func();

As other people stated you can't really do this because arrays will degrade to pointers. 正如其他人所说,您不能真正做到这一点,因为数组会降级为指针。 the standard way to do this is to return a struct 执行此操作的标准方法是返回一个struct

struct array {
    void* ptrs[5];
}

then your procedure would be declared like 那么你的程序将被声明为

struct array foo() {...}

Example: 例:

void **function(int c)
{
    void **arrayOfVoidStars = (void **)malloc(c*sizeof(void *));
    /* fill the array */
    return arrayOfVoidStars;
}

Functions cannot return array types. 函数不能返回数组类型。 You can either return a pointer to the first element of the array (type void ** ), or you can return a pointer to the whole array (type void (*)[N] ). 您可以返回指向数组第一个元素的指针(类型为void ** ),也可以返回指向整个数组的指针(类型为void (*)[N] )。 Note that the address value is the same either way (the address of the first element of the array is also the address of the array), it's just a difference in types. 请注意,地址值是相同的(数组的第一个元素的地址也是数组的地址),只是类型上的差异。

To return a pointer to a SIZE-element array of pointer to void , the function signature would be 要返回指向指向void的SIZE元素数组的指针,函数签名应为

void *(*func())[SIZE]

which breaks down as 分解为

        func             --  func
        func()           --  is a function
       *func()           --  returning a pointer
      (*func())[SIZE]    --  to a SIZE-element array
     *(*func())[SIZE]    --  of pointer
void *(*func())[SIZE]    --  to void.

Remember that postfix operators such as [] and () have higher precedence than unary operators such as * , so *a[] is an array of pointer and (*a)[] is a pointer to an array. 请记住,诸如[]()类的后缀运算符比*等一元运算符具有更高的优先级,因此*a[]是指针数组,而(*a)[]是指向数组的指针。

For C89 and earlier, SIZE must be a compile-time constant expression. 对于C89和更早版本,SIZE必须是编译时常量表达式。 For C99 you can use a variable expression. 对于C99,您可以使用变量表达式。

Whatever you do, don't try to return a pointer to an array that's local to the function, such as 无论您做什么, 都不要尝试返回指向函数本地数组的指针,例如

void *(*func())[SIZE]
{
  void *foo[SIZE];
  ...
  return &foo;
}

or 要么

void **func()
{
  void *foo[SIZE];
  ...
  return foo;
}

Once the function exits, foo ceases to exist, and the pointer value returned no longer points anywhere meaningful. 一旦函数退出, foo就不再存在,并且返回的指针值不再指向有意义的任何地方。 You're either going to have to declare the array as static in your function, or you're going to have to dynamically allocate it: 您要么必须在函数中将数组声明为static数组,要么要动态分配数组:

void *(*func())[SIZE]
{
  void *(*foo)[SIZE] = malloc(sizeof *foo);
  ...
  return foo;
}

or 要么

void **func()
{
  void **foo = malloc(sizeof *foo * SIZE);
  ...
  return foo;
}

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

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