variables vary mysteriously

Question: what is causing these values to change randomly?


My Code:

int q = nonZero;
for(j = nonZero;j>1;j--)
    printf("Top: %i %i\n",j,q);
    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 that tree[] is an array of Nodes, but the statement tree[0] = &t; rather suggests that it is an array of pointers. That being then case then:

qsort( tree, j, sizeof(&Node), cmp ) ;

or better

qsort( tree, j, sizeof(*tree), cmp ) ;

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 t to a variable with greater scope than t is also doomed.

I'm not sure if it's your problem, but since t is a local variable, it will go out of scope at the end of that loop, and so assigning it to tree[0] makes tree[0] undefined.

Need Your Help

Windows Vista and 7 motion effects are applied only once when my form is shown. Why?

windows delphi animation window aero

I created an application with two forms. First one is the main form and second one is hidden.

What is the maximum number of files that can be built at once in Netbeans 7.2

netbeans netbeans-7 netbeans-platform netbeans-7.2

I have a project that has approximately 2000 files (not including library files) that I want to build.