I want to be able to call a function to do something with a struct kind of like a class's methode with the self argument in python.
Something like this: struct.doSomethingWithStruct()
where doSomethingWithStruct doesn't need to have &struct passed to it in order to do something with it.
I tried to make a function that returns another function with the struct build into it but every time i call it, it modifies struct1* S
for all other structs too because functionBuilder returns a pointer to the same function every time.
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int x;
void* (*print)(int x);
} struct1;
void* functionBuilder(struct1* s){
void printStruct1(int a){
struct1* S = s;
printf("%d\n", a+S->x);
}
return printStruct1;
}
struct1* structBuilder(int x){
struct1* temp = malloc(sizeof(struct1));
temp->x = x;
temp->print = functionBuilder(temp);
return temp;
}
int main() {
struct1 *s1 = structBuilder(10);
struct1 *s2 = structBuilder(20);
s1->print(1);
s2->print(2);
free(s1);
free(s2);
return 0;
}
This code prints:
21
instead of
11
22
I've tried to allocate memory for struct1* S
but that also didnt work.
I've been trying to find a way for functionBuilder to return a unique function each time but i'm new to C and I havn't managed to find a way to do this yet.
If anyone knows how to do this or something else that also work please provide an explenation of how it works because im new to C and like to learn new things.
PS: I'm new to stackoverflow and if there is any way for me to improve this question please tell me how.