Skip to content

Instantly share code, notes, and snippets.

@shelling
Last active August 29, 2015 14:04
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 shelling/7fe98b9ab41826870e9a to your computer and use it in GitHub Desktop.
Save shelling/7fe98b9ab41826870e9a to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char*
itos(int value) {
char* result = malloc(sizeof(char)*100);
sprintf(result, "%d", value);
return result;
}
typedef struct {
char* value;
int length;
} String;
String*
new_string(char* value) {
String* result = malloc(sizeof(String));
result->value = value;
result->length = strlen(value);
return result;
}
String*
set_string(String* obj, char* value) {
obj->value = value;
obj->length = strlen(value);
return obj;
}
void
inspect_string(String* obj) {
puts(obj->value);
puts(itos(obj->length));
}
int main() {
String* hello = new_string("hello, world!");
inspect_string(hello);
set_string(hello, "I am Shelling!");
inspect_string(hello);
free(hello);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tree Tree;
struct tree {
char* data;
Tree* left;
Tree* right;
Tree* parent;
};
Tree*
tree_new(char* value) {
Tree* obj = malloc(sizeof(Tree));
obj->data = value;
return obj;
}
void
tree_left_set(Tree* base, Tree* left) {
base->left = left;
left->parent = base;
}
void
tree_right_set(Tree* base, Tree* right) {
base->right = right;
right->parent = base;
}
void
tree_traverse(Tree* obj, int (*function)(const char*)) {
if (obj) {
(*function)(obj->data);
tree_traverse(obj->left, function);
tree_traverse(obj->right, function);
}
}
void
tree_inspect(Tree* obj) {
tree_traverse(obj, puts);
}
int main() {
Tree* root = tree_new("root");
tree_left_set(root, tree_new("left"));
tree_right_set(root, tree_new("right"));
tree_inspect(root);
tree_inspect(root->left->parent);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment