开发者

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

I want to开发者_运维知识库 return an array of pointers to void. How do I specify this in the function prototype?

int*[] func();


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]). 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 *(*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.

For C89 and earlier, SIZE must be a compile-time constant expression. For C99 you can use a variable expression.

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. 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:

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

or

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


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 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜