#: 8674 S3/Languages
10-Dec-90 22:24:09
Sb: #Dynamic Structure Alloc
Fm: Jay Truesdale 72176,3565
To: all
I am writing a program that builds a b-tree using malloc to allocate
memory to hold a structure that is then referenced via pointers. The
C books I have don't cover this sort of thing, I'm trying to figure
out the "proper" way to reference the "next" structure item via the
pointer links. The stucture template looks like this:
struct b_tree_rec
{
int key;
struct b_tree_rec *lp; /* Left Pointer */
struct b_tree_rec *rp; /* Right Pointer */
}
In main() I declare these variables:
struct b_tree_rec node, *root_ptr, *node_ptr;
I allocate memory to hold the root node like this:
root_ptr = (struct b_tree_rec *) malloc(sizeof (node));
if (root_ptr == NULL)
{
printf("Error number %d in allocation of root node\n", errno);
exit(0);
}
root_ptr->key=0; /* init root node contents */
root_ptr->lp=NULL;
root_ptr->rp=NULL;
I'm not sure why the example code I looked at casts the pointer
returned by malloc as it did but I figure at least it provides more
documentation as to what is doing on. It also ocurred to me that if
pointer arithmetic is used the compiler needs to know how big the
pointed to object is. Am I correct in my assumption or is there more
to this?
How do I reference the fields in the second node?
This fails at execution time and I think I see why:
node_ptr->lp->lp=NULL;
This fails at compile time but I'm not sure what to try next.
(*(node_ptr->lp))->lp=NULL;
Suggestions? Any books that cover this sort of thing that anyone can
recommend?
Thanks, -J
There are 2 Replies.
|