As another Javascript developer learning C, I'm trying to implement a basic object.
UserStruct.h
#ifndef USERSTRUCT_H
#define USERSTRUCT_H
struct User {
int age;
int (* getAge)();
};
typedef struct User User;
int getAge(User);
User initUser(int);
#endif /* USERSTRUCT_H */
UserStruct.c
#include "./UserStruct.h"
int getAge(User this) {
return this.age;
}
User initUser(int age){
User user;
user.age = age;
user.getAge = getAge;
return user;
}
main.c
#include <stdio.h>
#include <stdlib.h>
#include "./UserStruct.h"
int main(int argc, char** argv) {
User user = initUser(15); // sets age to 15..
user.age = 2222;
printf("%d\n",user.getAge(1234)); // note the int passing here..
printf("%d\n",user.age);
return (EXIT_SUCCESS);
}
Questions!:
1. Can someone explain the syntax int (* getAge)();
inside the UserStruct definition?
2. getAge expects a User
to be passed to it, how come it works with an int
being passed in? This is especially strange as the implementation of getAge uses return this.age
.
While I did figure out how to fix it, I'm still not sure why this behaves the way it does. (The solution is to pass a pointer of the User into getAge)