J.Kennsy
J.Kennsy

Reputation: 618

Passing BST to struct array

I' would like to write a function that will pass all words and values from BST to struct array. In tree I have words(node->word) and value(node->val).
In main I declare array of pair struct.

Here is my code:

void inOrder(Tree *node,pair *array[], int index)
{
    if(node == NULL){  // recursion anchor: when the node is null an empty leaf was reached (doesn't matter if it is left or right, just end the method call
       return;
    }
    inOrder(node->left, array, index);   // first do every left child tree
    array[index]->val= node->val;   // then write the data in the array
    array[index]->word = malloc(sizeof(char)*(strlen(node->word)+1));
    strcpy(array[index]->word,node->word);
    index++;
    inOrder(node->right, array, index);  // do the same with the right child
}

int main(int argc, char *argv[])
{

    Tree *myTree = NULL;
    pair arr[5000];
    int index=0;
    ...
    inOrder(myTree,&arr,index);
    printf("%d",arr[0].val);
    zero(myTree);
    return 0;
}

Debugger says:

Access violation writting location 0x0000001.

Upvotes: 0

Views: 226

Answers (1)

sudo
sudo

Reputation: 5784

Something is weird with the pointers here. Your inOrder function header expects an array of pair pointers, but you pass in a pointer to an array of pairs (which is actually just a chunk of random memory). I'm pretty sure that's where the pointer error comes from.

There are many ways to fix this, but I'll just put the one I like the best. Any reason why you're passing a pointer to a pointer instead of just the pointer? Try changing your function header:

void inOrder(Tree *node, pair *array, int index)

and access stuff like this:

array[index].val= node->val;   // then write the data in the array
array[index].word = malloc(sizeof(char)*(strlen(node->word)+1));
strcpy(array[index].word,node->word);

and call it from main like this:

inOrder(myTree,arr,index);

I can't test it, unfortunately, but I think it should work.

P.S. Sorry for all the edits/deletions. I misread something.

Upvotes: 1

Related Questions