Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specific condition not working in my do-while loop?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading