Skip to content

Instantly share code, notes, and snippets.

@hoenirvili
Created September 26, 2015 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hoenirvili/71508dffc47b4b1293a9 to your computer and use it in GitHub Desktop.
Save hoenirvili/71508dffc47b4b1293a9 to your computer and use it in GitHub Desktop.
Struct pointer demo
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
/**
* Mini wrapper function for malloc
*/
void* Malloc(size_t size) {
void *vptr = malloc(size);
if(vptr != NULL)
return vptr;
else
assert(false);
}
typedef struct Person {
char *name;
int age;
int height;
int weight;
}Person;
Person *Person_create(char *name,int age, int height, int weight) {
Person *who = Malloc(sizeof(Person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight = weight;
return who;
}
void Person_destroy(Person *who) {
assert(who != NULL);
//very important if we have
//members also pointer
//we have also need to free them
free(who->name);
free(who);
}
void Person_print(Person *who) {
printf("Name : %s\n", who->name);
printf("tAge: %d\n", who->age);
printf("theight: %d\n", who->height);
printf("tweight: %d\n", who->weight);
printf("\t Sizeof Person = %lu\n",sizeof(*who));
}
int main(int argc, char *argv[]) {
Person *joe = Person_create("Joe Alex", 32, 64, 140);
Person *brad = Person_create("Brad Pit", 42, 68, 160);
printf("Joe is at memory location %p:\n",joe);
Person_print(joe);
printf("Brad is at memory location %p:\n",brad);
Person_print(brad);
Person_destroy(joe);
Person_destroy(brad);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment