Skip to content

Instantly share code, notes, and snippets.

@ermiry
Last active November 17, 2019 01:04
Show Gist options
  • Save ermiry/bc6f5689cf78dd49117de0658e440a9b to your computer and use it in GitHub Desktop.
Save ermiry/bc6f5689cf78dd49117de0658e440a9b to your computer and use it in GitHub Desktop.
User Structure Example
#include <stdlib.h>
#include <string.h>
typedef struct User {
char *name;
int id;
} User;
static User *user_new (char *name, int id) {
User *user = (User *) malloc (sizeof (User));
if (user) {
if (name) {
size_t len = strlen (name);
user->name = (char *) calloc (len + 1, sizeof (char));
strcpy (user->name, name);
}
else user->name = NULL;
user->id = id;
}
return user;
}
static inline void user_delete (void *user_ptr) {
if (user_ptr) {
User *user = (User *) user_ptr;
if (user->name) free (user->name);
free (user_ptr);
}
}
static int user_comparator (const void *user_ptr_a, const void *user_ptr_b) {
User *user_a = (User *) user_ptr_a;
User *user_b = (User *) user_ptr_b;
if (user_a->id < user_b->id) return -1;
if (user_a->id == user_b->id) return 0;
else return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment