简体   繁体   中英

For Loop in C does not work as Expected

I don't understand the flow of the following for loop: it becomes an infinite loop. I am using ubuntu 12.04. Am I doing anything wrong here?

#include <stdio.h>
main()
{
    int k,a[10];
    for(k=0; k<=10; k++)
    {
        a[k]=1;
        printf("k = %d\n",k);
    }
}

Once k == 9 , it automatically changes to 1 . I don't know why it behaves like this. What am I doing wrong?

 for(k=0; k<=10; k++)

This access out of bound index . a[10] (indexing start with 0 therefore valid index 0-9 ) is out of bound and invoke undefined behaviour .

loop should be this -

 for(k=0; k<10; k++)

Your operating system doesn't affect the way the loop is processed. What you need is a way to handle the integer variable "k" and inside the loop, you need to make "k" greater than 10 for the loop to exit properly. So I made K increment so that each element of the integer array "a" contains the value 1.

#include <stdio.h>
int main()
{
int k,a[11];
for(k=0; k<=10; k++)
{
    a[k]=1;
    printf("k = %d\n",k);
    k++;
}
return 0;
}

Actually array index starts from 0. So if you have an array "a" with 10 members in it, then the members will be

1st member - a[0]; 2nd member - a[1]; 3rd member - a[2]; ... ... ... 10th member - a[9]

So, you can't have a member a[10]. But in your for loop you started k from 0 and incremented it to 10. But a[10] was not present in the array and this caused the infinite loop. To solve this problem, just use "k<10" as your loop condition. Your code should look like this now:

#include <stdio.h>
main()
{
    int k,a[10];
    for(k=0; k<10; k++)
    {
        a[k]=1;
        printf("k = %d\n",k);
    }
}

The reason k is becoming 1 after 9 is that for some reason k is situated right after the memory range of a. So, when you change a[10] to 1, it actually changes the value of k. So, you get 1 as the value of k.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM