简体   繁体   中英

array pointer type for function return

I started using array pointers a lot recently because it simplify a lot the allocation/deallocation, but the type always throw an error by the compiler when its the return type of a function. this is accepted:

int (*arr_ptr)[SIZE] = NULL;

but this is not:

int (*)[] foo(void) {
    return NULL;
}

the compiler throw this error:

src/main.c:51:7: error: expected identifier or ‘(’ before ‘)’ token
   51 | int (*)[] foo(void) {
      |       ^

For the moment I just typedef the type and it work:

typedef int(*tdarr_ptr_int)[];
tdarr_ptr_int foo(void) {
    return NULL;
}

But this not a suitable longterm solution for me, how can I specify this return type without having to typedef it?

C uses infix notation, as we saw from your first example:

int (*arr_ptr)[SIZE] = NULL;

is correct whereas

int (*)[SIZE] arr_ptr = NULL;

is not. You can fix the function version by applying the same principle:

int (*foo(void))[] {

NB. People sometimes criticize the infix, saying that postfix is easier, but hopefully it is clear from this example that the only difference is the placement of the identifier, and in fact having the identifier in the infix position helps you see where the middle is:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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