Specific condition not working in my do-while loop?

Advertisements
int dbgEnter(int measurements[], int *nr)
{   
    int i = 0;

    do
    {
        printf("Enter Measurement #%d: ", i+1);
        scanf("%d", &measurements[i]);

        i++;
        int *nr = &i;
        
    } while (i < MAX && measurements[i] != 0);

For some reason measurements[i] != 0 doesn’t seem to register as a condition for the while-loop. I tried it inside do with an if-condition (having it print something random) and it worked flawlessly. Can anyone please help me identify the problem?

>Solution :

You increase i before checking if the entered value is 0:

   // ...
   i++;        
} while (i < MAX && measurements[i] != 0); // measurements[i] is uninitialized

You are also storing the address of the local variable i in int *nr = &i;. There are two problems with that:

  • The nr you declare in the loop is not the same nr as your function takes as an argument. nr in the loop shadows the function argument.
  • If you removed the declaration and just made it nr = &i; then nr would store the address of the local variable i and return that address to the caller of the function. This address is of no use once the function returns and dereferencing nr after the function has returned leads to undefined behavior.

Leave a ReplyCancel reply