Question: what is causing these values to change randomly?
Info:
My Code:
int q = nonZero;
for(j = nonZero;j>1;j--)
{
printf("Top: %i %i\n",j,q);
qsort(tree,j,sizeof(Node),cmp);
printf("Bottom: %i %i\n",j,q);
Node t = {tree[0],tree[1],-1};
tree[0] = &t;
tree[1] = tree[j];
tree[j] = NULL;
}
Not a complicated little program. make a node out of the top two nodes on the tree, make that the new top node, resort the array, repeat. I added ‘q’ in as a debug value, I’m completely clueless as to what exactly is happening. If I try and have it run, j typically starts at 73, which it should, the expected is that it would then be 72,71,70,69,68…3,2 and that q will remain 73 indefinitely. here’s my output though:
Top: 73 73
Bottom: -796584576 32767
Segmentation fault
but thats not all, w/o recompiling, i got:
Top: 73 73
Bottom: 0 0
Segmentation fault
it consistently would give me one of those two outputs. after several runs I saw that 32767 never changed, the q value, but the j value, here -796584576, was always some different absurdly large negative number. anyone have any idea why on earth it would seem as if qsort was changing my j value, as well as what seems to be a completely unrelated value of q?
The
qsort()call suggests thattree[]is an array ofNodes, but the statementtree[0] = &t;rather suggests that it is an array of pointers. That being then case then:or better
the latter ensures the size is the sizeof whatever tree is an array of regardless of its type and is therefore safer and more maintainable.
Assigning the address of
tto a variable with greater scope thantis also doomed.