1

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?

Tono Nam
  • 34,064
  • 78
  • 298
  • 470
  • 4
    Because you're not allowed to define a function within another function. GCC allows this as an [extension](https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html), but it fails on [other compilers](https://godbolt.org/z/xsTnjMjaK). Even on GCC, you're not allowed to call the nested function after its containing function exits. – Miles Budnek Jun 04 '22 at 18:39
  • 1
    (Last comment deleted, I misread the code.) -- Also, your inline_helper is a variable on the stack. You assign the pointer to a variable on the stack to the struct. When you leave the function you should not access the pointer to a now potentially overwritten stack address. So the way I read it no, it is definitely not safe. – PhilMasteG Jun 04 '22 at 18:41
  • https://www.techbeamers.com/implement-a-c-class-using-c-struct/ – pm100 Jun 04 '22 at 18:52
  • You may want to learn C++ (very complex language) not C. You may want to invent your own language and implement a translator to C. – Basile Starynkevitch Jun 04 '22 at 19:27
  • 1
    See my answer for some ways to do this. Not quite what you want, but C isn't quite C++: https://stackoverflow.com/questions/65621027/writing-a-generic-struct-print-method-in-c/65621483#65621483 – Craig Estey Jun 04 '22 at 19:41

0 Answers0