I have a struct as follows, with a pointer to a function called \"length\" that will return the length of the chars member.
typedef struct pstring_t {
ch
You can use also "void*" (void pointer) to send an address to the function.
typedef struct pstring_t {
char * chars;
int(*length)(void*);
} PString;
int length(void* self) {
return strlen(((PString*)self)->chars);
}
PString initializeString() {
PString str;
str.length = &length;
return str;
}
int main()
{
PString p = initializeString();
p.chars = "Hello";
printf("Length: %i\n", p.length(&p));
return 0;
}
Output:
Length: 5