Solution for Exercise 09_06-prtstruct.c
09_06-prtstruct.c
#include <stdio.h>
char *hello(void)
{
return("Hello, ");
}
char *world(void)
{
return("world!\n");
}
int main()
{
struct msg {
char *(*f1)();
char *(*f2)();
} func;
func.f1 = &hello;
func.f2 = &world;
printf("%s%s",func.f1(),func.f2());
return 0;
}
Output
Hello, world!
Notes
* The first major change is the data type for both functions. In the source code file 09_05-structptr.c (in the book), these are both void functions. In the solution file, they must be char * (character pointers). Each returns the address of a string.
* To properly type the member sof the msg structure, each must be set as a character pointer function that requires no arguments: char *(*f1)() and char *(f2)()
* Yes you, can specify void in the pointer/function members: char *(*f1)(void) and char *(f2)(void)
* The assignments may have thrown you. Because the functions return a pointer, they must be assigned to the address of an address: func.f1 = &hello; and func.f2 = &world; The & (address-of) operator is required because the function itself is an addresss but it returns an address. So it's an address of an address, which is that double-pointer nonsense.
* Refer to the book for more details on dealing with double pointers.
Copyright © 1997-2025 by QPBC.
All rights reserved
