/** * Don't make assumptions about malloc. */ // +---------+------------------------------------------------------- // | Headers | // +---------+ #include #include #include // +-----------+----------------------------------------------------- // | Constants | // +-----------+ // Maximum lengh of strings #define MAXLEN 31 // Number of children in a node #define ARITY 5 // +-------+--------------------------------------------------------- // | Types | // +-------+ struct StringPair { char str1[MAXLEN+1]; char str2[MAXLEN+1]; }; struct Node { struct Node *children[ARITY]; }; // +-----------+----------------------------------------------------- // | Functions | // +-----------+ /** * Allocate and initialize a new StringPair struct. Returns NULL if * allocation fails. */ struct StringPair * string_pair_new (char *str1, char *str2) { struct StringPair *result = malloc (sizeof (struct StringPair)); if (NULL == result) return NULL; strncpy (result->str1, str1, MAXLEN); result->str1[MAXLEN] = 0; strncpy (result->str2, str2, MAXLEN); result->str2[MAXLEN] = 0; return result; } // string_pair_new /** * Determine if a node has chldren. */ int has_children (struct Node *node) { if (NULL == node) return 0; int i; for (i = 0; i < ARITY; i++) { if (node->children[i] != NULL) return i+1; } // for return 0; } // has_children // +------+---------------------------------------------------------- // | Main | // +------+ int main (void) { int ARRAY_SIZE = 10; int i; struct StringPair *pairs[ARRAY_SIZE]; struct Node *nodes[ARRAY_SIZE]; /* // Create a bunch of string pairs for (i = 0; i < ARRAY_SIZE; i++) { pairs[i] = string_pair_new ("alpha", "beta"); } // for // Free all of the string pairs for (i = 0; i < ARRAY_SIZE; i++) { free (pairs[i]); } */ // Create a bunch of nodes for (i = 0; i < ARRAY_SIZE; i++) { nodes[i] = malloc (sizeof (struct Node *)); } // for // Check if any have dhildren for (i = 0; i < ARRAY_SIZE; i++) { if (has_children (nodes[i])) { fprintf (stderr, "Node %d has children.\n", i); } // if } // for // And we're done return 0; } // main