Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare function return type `int (*)[3]`?

Tags:

c

int (*)[3] foo (); doesn't work.

How to declare function return pointer to array of 3?

It might not be useful, but I want to know if it's possible.

like image 688
Lukas.J Han Avatar asked Aug 26 '26 07:08

Lukas.J Han


1 Answers

First, I agree with the other answers that you probably need a typedef or a struct in there to clarify.

If you want to know how to declare the return type, it's int (*foo(void))[3] {

In the "declaration reflects use" pattern, you can build this up by considering the usage, i.e. how to get from foo's type to the plain type int:

  • take foo
  • call it (with no arguments): foo()
  • dereference the return value: *foo()
  • add an array index: (*foo())[i]; the parentheses are needed because the postfix syntax would otherwise take precedence over prefix one.
  • the result is of plain type int

Declaration reflects it:

  • take foo
  • call it: foo(void), inserting void to say it's specifically a 0-param function rather than one with an unspecified set of parameters
  • dereference the function return value: *foo(void)
  • add an array index: (*foo(void))[3], making the "index" be the size of the array
  • we got down to the plain type, so declare that the thing you built has that type: int (*foo(void))[3]

Example code:

#include <stdio.h>
int arr[3];
int (*foo(void))[3] {
  return &arr;
}
int main (void) {
  arr[0] = 413;
  arr[1] = 612;
  arr[2] = 1025;
  printf("%d %d %d\n", (*(foo()))[0], (*(foo()))[1], (*(foo()))[2]);
  return 0;
}

Side note: be sure that the array you are returning a pointer to will continue to exist after the function returns.

like image 101
Simon Clarkstone Avatar answered Aug 29 '26 04:08

Simon Clarkstone