Created
May 9, 2025 17:23
-
-
Save iKunalChhabra/ca078901dfdc462dc3f8e55099c717a3 to your computer and use it in GitHub Desktop.
Create objects in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| typedef struct person | |
| { | |
| const char* name; | |
| int age; | |
| void (*print)(struct person*); | |
| } person_t; | |
| void print_person(person_t* person){ | |
| printf("Person(name=%s, age=%d)\n", | |
| person->name, person->age); | |
| } | |
| person_t* create_person(const char* name, int age){ | |
| person_t* person = malloc(sizeof(person_t)); | |
| person->name = strdup(name); | |
| person->age = age; | |
| person->print = print_person; | |
| return person; | |
| } | |
| void destroy_person(person_t* person){ | |
| free((void*)person->name); | |
| free(person); | |
| } | |
| int main(){ | |
| person_t* person = create_person("Jack", 27); | |
| person->print(person); | |
| destroy_person(person); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment