I am new to C. (I'm using C89 on Visual Studio 2010.) I wrote a little program that uses a tree to give a histogram of arguments presented to the program. Are there any obvious beginner mistakes I've make? Everything appears to run fine in my extremely limited testing.
hist.c
#include "tree.h"
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
unsigned int i;
struct tree *tree;
tree = NULL;
for (i = 1; i < argc; i++) {
tree = tree_add(tree, argv[i]); // adds strings to tree
}
tree_dump(tree); // prints results
tree_free(tree); // frees memory
getchar();
return 0;
}
tree.h
struct tree {
struct tree *left;
struct tree *right;
char *value;
unsigned count;
};
struct tree *tree_add(struct tree *tree, char *value);
struct tree *new_tree();
void tree_dump(struct tree *tree);
void tree_free(struct tree *tree);
tree_free.c
#include "tree.h"
#include <stdlib.h>
void tree_free(struct tree *tree) {
if (tree->left != NULL) {
tree_free(tree->left);
}
if (tree->right != NULL) {
tree_free(tree->right);
}
free(tree);
}
tree_dump.c
#include "tree.h"
#include <stdlib.h>
#include <stdio.h>
void tree_dump(struct tree *tree) {
if (tree != NULL) {
tree_dump(tree->left);
printf("%4u\t%s\n", tree->count, tree->value);
tree_dump(tree->right);
}
}
tree_add.c
#include "tree.h"
#include <stdlib.h>
#include <string.h>
struct tree *tree_add(struct tree *tree, char *value) {
if (tree == NULL) {
tree = new_tree();
tree->value = value;
tree->count = 1;
}
else if (strcmp(tree->value, value) == 0) {
tree->count++;
}
else if (strcmp(value, tree->value) < 0) {
tree->left = tree_add(tree->left, value);
}
else if (strcmp(value, tree->value) > 0) {
tree->right = tree_add(tree->right, value);
}
return tree;
}
struct tree *new_tree() {
struct tree * tree;
tree = malloc(sizeof *tree);
tree->left = NULL;
tree->right = NULL;
tree->value = NULL;
tree->count = 0;
return tree;
}