c - Parsing an uninitialized value into a function -
i'm trying write little program goes through list of numbers in array , inserts them binary search tree. here's have:
#include <stdio.h> #include <stdlib.h> typedef struct node_t node_t; struct node_t { int data; node_t *left; node_t *right; }; int insert(node_t *node, int n); int main(void) { int array[8] = {5, 8, 3, 6, 9, 2, 4, 7}; int i; node_t *root; (i = 0; < 8; i++) { insert(root, array[i]); } return 0; } int insert(node_t *node, int n) { if (node == null) { node = malloc(sizeof node); node->data = n; return 1; } if (n > node->data) { insert(node->left, n); } else if (n < node->data) { insert(node->right, n); } else { return -1; } return 0; // suppress 'control reaches end of non-void function' }
when compile gcc warning saying "'root' may used uninitialized in function". running causes on errors (on windows @ least), however, printing out root->data
in main()
yields 0.
the idea trying implement insert()
function checking if pointer input node null
malloc it. also, due how recursion handled, number being inserted should inserted @ node. if node did not equal null
, recursively call insert()
again on side of node number should inserted.
i understand reason why doesn't work has pointer root
not being directed anywhere, nor root->left
/root->right
, however, don't know can fix this. appreciated, thank you!
there might more problem code posted listed few problems below.
since node need allocate memory if contains null, need change this:
if (node->data == null) {
to this:
if (node == null) {
also, need initiate root node, since contain whatever happens on stack @ moment , may or may not null (e.i. thing want compare in insert function). initiate so:
node_t *root = null;
last thing change malloc calloc function (or memset 0 on memory separately). otherwise variables node->left , node->right can contain non null values result in making use of uninitialized memory.
Comments
Post a Comment