1

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.

user1138143
  • 81
  • 1
  • 12

3 Answers3

6

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.

Community
  • 1
  • 1
Natasha Dutta
  • 3,242
  • 21
  • 23
  • @NatashaDutta But when you show some statement and say it is a function pointer it is misleading – Gopi Dec 05 '14 at 10:46
  • I do understand that struct char was invalid. I was trying to give some var name, but my mistake given the char word. I have updated the question. – user1138143 Dec 05 '14 at 11:41
2

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!");
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks for your reply!! I do understand that struct char was invalid. I was trying to give some var name, but my mistake given the char word. Correct one : void (*myvar)(const struct foo *); – user1138143 Dec 05 '14 at 11:43
2

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.

Abhineet
  • 5,320
  • 1
  • 25
  • 43