NO

Author Topic: How to make structure with function pointers?  (Read 1358 times)

Offline bitcoin

  • Member
  • *
  • Posts: 179
How to make structure with function pointers?
« on: January 24, 2020, 04:31:31 PM »
Hello.
I read this article  , there is a code

Code: [Select]
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
    printf("Value of a is %d\n", a);
}
 
int main()
{
    // fun_ptr is a pointer to function fun() 
    void (*fun_ptr)(int) = &fun;
 
    /* The above line is equivalent of following two
       void (*fun_ptr)(int);
       fun_ptr = &fun; 
    */
 
    // Invoking fun() using fun_ptr
    (*fun_ptr)(10);
 
    return 0;
}

How I can change it, to make structure with function pointers? I want to make a sample OOP , such as String->strlen, String->strcat

This code dont work. How to make structure, that contains function pointers and can call functions?

Code: [Select]
typedef struct _api
{
   void * f1;
   void * f2;

} apis;

apis api;

int main()
{
(*api.f1) = &fun;

(*api.f1)(22); //Don't work!!!

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2096
Re: How to make structure with function pointers?
« Reply #1 on: January 24, 2020, 04:50:44 PM »
A function pointer isn't a void pointer!
You can't declare it so, you must declare as function pointer:
Code: [Select]
#include <stdio.h>
#include <string.h>

typedef struct _api {
int (*s_len) (char *);
void (*s_print) (char *);

} apis;

apis api;

int my_str_len(char *s)
{
return strlen(s);
}

void my_print_string(char *s)
{
puts(s);
}

int main(void)
{
api.s_len = my_str_len;
api.s_print = my_print_string;

char string[] = "Hello World!";

api.s_print(string); //prints "Hello World!"
printf("The string \"%s\" is %d characters in length.\n", string, api.s_len(string));
}

« Last Edit: January 24, 2020, 05:26:56 PM by frankie »
It is better to be hated for what you are than to be loved for what you are not. - Andre Gide

Offline bitcoin

  • Member
  • *
  • Posts: 179
Re: How to make structure with function pointers?
« Reply #2 on: January 24, 2020, 05:42:40 PM »
Thank you , it works!

i forgot to post link to article in first post) There is https://www.geeksforgeeks.org/function-pointer-in-c/