开发者

Why put a '*' on functions that return a struct pointer?

I ran into a problem where I declared a function this way:

struct my_struct get_info();

It's supposed to return a pointer to a struct, and then in main that pointer is captured, like so:

struct my_struct *p_struct;
p_struct = get_info();

Then I got a compiler error saying that it could not convert from 'my_struct *' to 'my_struct. I looked around at code that does the same thing and I noticed that in their function prototype and definition they had an * before the function name, like:

struct my_struct *get_info();

After I added in 开发者_如何学Cthe *, everything was fine. I don't know why it fixes it though, and why you would do that. Do you only do that when returning a struct pointer? Or are there other cases you would want to do that? Thanks.


It's supposed to return a pointer to a struct

But your code is not returning a pointer to struct. Is it?

Didn't you mean struct my_struct* get_info(); ?


struct my_struct* denotes a pointer, simple as that. So when you want to return a pointer, the return type should be a pointer aswell, no?
You can write that struct my_struct *get_info(); as struct my_struct* get_info();, which may hint more at what the real return type is for you. The * belongs to that return type, not to the function itself.


You can pass (struct)s around by value instead of as pointers. It's usually not a good idea (use references, or pointers if you must, instead). So you need to use & for reference or * for pointer, or it will expect you to return it by value.


The bottom line seems to be that your code was inconsistent - saying "return pointer-to-struct-variable" in a function declared to return a struct directly. They are different things. You seem to think the compiler could guess or know which was a mistake, perhaps thinking that people always return structs by pointer, but this isn't true and indeed the compiler can't know for sure, so the best thing it can do to ensure the program works as intended is insist that you - the programmer - return to the code and make it consistent.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜