Declaring a function pointer returning an array

匿名 (未验证) 提交于 2019-12-03 02:43:01

问题:

For practice, I'm trying to :

Declare fubar to be a pointer to a function that takes a pointer to a char and returns a pointer to an array of 24 elements where each element is a pointer to a struct foo.

My logic is:

-fubar is a pointer to a function taking a char pointer: (*fubar)(char*)

-...returning a pointer to an array of 24 elems of where each elem is a struct foo:

(struct foo *)(*fubar)(char*)[24]

Is my logic correct?

回答1:

After fixing the syntax error and removing the parentheses around struct foo *,

struct foo* (*fubar)(char*)[24]

...the one part that you got wrong is that it actually returns an array of pointers, not a pointer to an array. In order to declare a pointer to the array, you need an extra set of parentheses:

struct foo (*(*fubar)(char*))[24]

You can pretend that that the star belongs to an identifier (i.e., the name of the array) inside the parentheses.



回答2:

Functions never return arrays, they may return a pointer (conventionally to the first cell of an array), since as return value or as argument an array decays to a pointer.

So, declare with a typedef the signature of your function:

typedef struct foo** funsig_t(char*);

notice that if you omit the typedef you would declare a function funsig_t of the desired signature.

then declare a pointer using that typedef:

funsig_t* fubar;


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!