I am in initial phase of learning C language. I have one doubt regarding a statement including void pointer.
void (*myvar)(const struct foo *);
Can anyone please help me about the above line. What is the exact meaning of above line and how do use this pointer in the code.
In your question,
void (*myvar)(const struct charpp *);
Follow the NOTE
is a function pointer, not a simple pointer -to -struct
. You can find more information regarding this here .
Also, do check this answer for a clear idea of the usage.
Note: char
is a reserved keyword [datatype] in c. It cannot be used as variable name, as you've used in your code. Change so something else.
That should be a variable declaration of a pointer to a function taking a const char *
as argument and not returning any value. I say should because you have an error in the declaration of the argument type (there's no such thing as const struct char *
).
If you fix the error, and assuming you mean const char *
, then you can use it like the following code:
#include <stdio.h>
void my_print_line(const char *str)
{
printf("%s\n", str);
}
int main(void)
{
void (*myvar)(const char *);
myvar = &my_print_line;
myvar("Hello world!");
}
It is a pointer to a function. You can break and understand the rule easily if you follow the Spiral Rule . Take a look at Example2. Now you can easily, put your declaration instead of the example and break it part by part to get better understanding.
+--------------------+
| +---+ |
| |+-+| |
| |^ || |
char *(*fp)( int, float *);
^ ^ ^ || |
| | +--+| |
| +-----+ |
+------------------------+
Also, struct char
will generate an error.
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.