-
Scope of arrays
Hello, I'm new to these forums and to C language. I'm writing a code for an algorithm and I'm having problem with my arrays. I believe the problem lies with pointers, since I've never studied them and still don't quite understand how they work.
Here's a section of the code in which I'm noticing problems
Code:
int U[x]; //set of searched nodes in X
int V[y]; //set of searched nodes adjacent to those in U
int R[y]; //set of adjacent nodes to those in U
step1: //Search X for labels, if all non-zero finish
u=0;
for(i=0;i<x;i++){
if(X[i].label==0){
U[u]=X[i].id;
printf("ID %d into U[%d]\n",U[u],u); //added to see what array does
u++;
for(z=0;z<y;z++){
V[z]=0;
}
v=0;
break;
} else if(i==x-1){
goto finish;
}
}
printf("ID %d into U[%d]\n",U[0],0); //see what values in array
so when i run this, the line within the loop prints the correct value for U[0], but as soon as it exits the loop the value for U[0] returns to 0.
How can I get it to store the values to U within the scope of the method?
Edit: I should probably also mention that the sizes of the arrays (x and y) are read in from a file
Thanks in advance, hope someone can help soon! gotta turn it in in a few hours
-
What you're saying is that the two lines print different values for U[0]
Code:
printf("ID %d into U[%d]\n",U[u],u); //for u=0
and
printf("ID %d into U[%d]\n",U[0],0);
This could be true only if the else if part is getting executed and the label "finish" is changing U[0]. So, where's "finish"?
-
hmm... well that's strange... it doesn't go into the else if since there's the break; statement, so after it sets the U it exits the loop. And btw, the finish is after all the loops before it prints out my final answer.. but it doesn't affect it at this point.
So what could be causing the problem? nothing touches U in between the two print lines... Do labels affect the scope of a variable?
-
I suggest that you post the smallest and simplest compilable program that demonstrates the problem. Feel free to hardcode the array sizes and other input. State the expected output and your actual output.
By the way, it is usually a good idea to avoid using goto.
-
haha... gotta love programming... thanks for your post, I discovered my problem was that I was actually initiating the arrays before reading in x and y.
and about the goto, I've read many say it's bad practice... but I can't really think of another way to do this. There's different steps to go to and many loops within each step, so the easiest way I can think of is using them.