[Solved] Infinite loop in C, what is wrong? [closed]


“Whenever i choose 1 as my parameter, i enter 3 as my instruction classes however i am unable to input the CPI of class 3 or even the instruction count of class 3. Once i input the CPI and instruction count of class 2 it ends.”

This is because you tell it to. Here:

for(a = 1; a < n; a++){

if you enter 3, then the loop runs once when a == 1, a second time when a == 2, and then quits, because a < 3 is no longer true. You want this:

for( a = 0; a < n; a++ ){      /*  Change a = 1 to a = 0  */
    printf(" Enter CPI of class %d : ", a + 1);
    scanf("%d", &CPI[a]);      /*  Change [a-1] to [a]  */

    printf(" Enter instruction count of class %d : ", a + 1);
    scanf("%d", &Count[a]);    /*  Change [a-1] to [a]  */
    tot += Count[a];           /*  Change =+ to += and [a-1] to [a]  */
}

Your code has lots of other problems, though, including the fact that the global variables CPI and Count that SelectTwo() appear to be using are not the same ones that SelectOne() is writing to, because in SelectOne() you create local variables of the same name which hide them.

EDIT: You edited your question to show the definitions of your global arrays:

int CPI[];
int Count[];

What this is actually doing is declaring an incomplete type, because you’re not providing a size. Once you get to the end of the translation unit, if the array still has an incomplete type, then it’s assumed to have one element, which is here set to zero on program startup. So you’re effectively creating one-element arrays, so attempting to loop over more than one element in SelectTwo() is just undefined and nonsensical behavior.

As mentioned, the CPI and Count that SelectOne() is using are not the same ones that you are defining globally, so SelectTwo() is not reading from what SelectOne() is writing to.

If you want to use global arrays like this, you have to provide a size, e.g.

int CPI[3];
int Count[3];

If you don’t want to provide a size (for instance, because here you want the user to choose the size), then you’ll have to either use malloc() or define a variable length array within a function and pass it to the functions that need it.

solved Infinite loop in C, what is wrong? [closed]