I wanted to create a function for my struct. I searched on the internet and found this two helpful links:
Most of the answers defined this:
typedef struct Point
{
int x;
int y;
void (*Print)(Point* p);
} Point;
Meaning that if you wanted to call the Print
function on a struct you will have to pass the same point again. In other words you would do something like this:
somePoint.Print(&somePoint);
That works but it will be better if you don't have to pass &somePoint
as an argument. In other words my goal is to achieve the same behavior by calling somePoint.Print();
instead of somePoint.Print(&somePoint);
.
Anyways I am no expert in C and I was about to post this answer on those links:
#include <stdlib.h>
#include <string.h>
typedef struct Point
{
int x;
int y;
void (*Print)();
} Point;
void _print_point(Point* p)
{
printf("x=%d,y=%d\n", p->x, p->y);
}
void Point_Constructor(Point* p, int x, int y){
p->x = x;
p->y = y;
// create wrapper function
void inline_helper() { _print_point(p);}
p->Print = inline_helper;
}
int main(){
Point p1;
Point_Constructor(&p1,1,2);
p1.Print(); // I CAN CALL THE PRINT FUNCTION WITHOUT HAVING TO PASS AGAIN THE SAME POINT AS REFERENCE
return 0;
}
Why nobody suggested that? Is it safe if I run code like that?