Vali RO
Vali RO

Reputation: 61

pointer to function in a struct in C

I need to create a struct which contains 1 int, 2 char, 1 float and (I write the lines from the exercise): "two pointers on functions for reading data void (read*)(student*st) and one pointer for displaying data void (write*)(student*st) "

I just don't understand the sentence. I know the syntax for a pointer to function in C. I don't get what read* and write* are. If it was *read and *write then in would be the pointer variable name to a function and (student*st) is the parameter, a pointer to struct.

Also, in the exercise appear that the program is about ANSI C but also it asks me to use cin to read the number of students and to allocate memory using new for an array of students.

This is how I started.

struct student {
    int idNumber;
    char name[100];
    char gender[20];
    float mark;
    ??
};

Upvotes: 2

Views: 505

Answers (1)

user10008009
user10008009

Reputation:

What's the problem with the following code sample? I only add one function pointer (func_print), but the code should be self explanatory:

#include <stdio.h>

struct student {
    int idNumber;
    char name[100];
    char gender[20];
    float mark;
    void (*func_print)(struct student *);
};

void print(struct student *s)
{
    printf("ID    : %d\n", s->idNumber);
    printf("Name  : %s\n", s->name);
    printf("Gender: %s\n", s->gender);
    printf("Mark  : %f\n", s->mark);
}

int main(int argc, char *argv[])
{
    struct student foo = { 0, "John Doe", "Male", 1.0, &print};
    
    foo.func_print(&foo);
    return 0;
}

Output:

$ ./foo
ID    : 0
Name  : John Doe
Gender: Male
Mark  : 1.000000
$

This technique is very often used in various C programs. (You have added the C tag, none C++ tag. So far other members wrote, std::cin and new are C++ only.)

Linux device driver structure (device_driver) as real world example:

struct device_driver {
    const char      *name;
    struct bus_type     *bus;

    struct module       *owner;
    const char      *mod_name;  /* used for built-in modules */

    bool suppress_bind_attrs;   /* disables bind/unbind via sysfs */
    enum probe_type probe_type;

    const struct of_device_id   *of_match_table;
    const struct acpi_device_id *acpi_match_table;

    int (*probe) (struct device *dev);
    void (*sync_state)(struct device *dev);
    int (*remove) (struct device *dev);
    void (*shutdown) (struct device *dev);
    int (*suspend) (struct device *dev, pm_message_t state);
    int (*resume) (struct device *dev);
    const struct attribute_group **groups;
    const struct attribute_group **dev_groups;

    const struct dev_pm_ops *pm;
    void (*coredump) (struct device *dev);

    struct driver_private *p;
};

Upvotes: 0

Related Questions