[ Home  |  FAQ-Related Q&As  |  General Q&As  |  Answered Questions ]


    Search the Q&A Archives


why this program goes to infinite loop #include<stdio.h&g...

<< Back to: Objective-C FAQ

Question by madhur
Submitted on 8/19/2003
Related FAQ: Objective-C FAQ
Rating: Rate this question: Vote
why this program goes to infinite loop
#include<stdio.h>
#include<conio.h>.
int arr[10];
int x;
void main(void)
         {
           for(x=1;x<=10;x++)
              arr[x]=-100
             getch();
         }


Answer by max
Submitted on 5/2/2004
Rating: Not yet rated Rate this answer: Vote
Because of a bug in it.

In C/C++/Obj-C and others, arrays starts at pos 0 not 1, your "for" statement should be

for(x=0;x<9;x++)

As for the fact it goes into loop (instead of a crash) is compiler related (or better global variables storage related).

What happens here is that when writing arr[10]=-100 you're actually overwriting the location where x is stored (that is right after your arr given the declaration) so making x=-100, at this point the next loop will go to arr[-100] writing back to arr[9], and then again restarting.

You are lucky there was not important data between location arr[-100] and arr[9], it there were, a crash would have been more than probable.


 

Answer by max
Submitted on 5/2/2004
Rating:  Rate this answer: Vote
Sorry about the again faulty correction

The fix for the loop is:

for(x=0;x<=9;x++)

or

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

Sorry 'bout that.

 

Your answer will be published for anyone to see and rate.  Your answer will not be displayed immediately.  If you'd like to get expert points and benefit from positive ratings, please create a new account or login into an existing account below.


Your name or nickname:
If you'd like to create a new account or access your existing account, put in your password here:
Your answer:

FAQS.ORG reserves the right to edit your answer as to improve its clarity.  By submitting your answer you authorize FAQS.ORG to publish your answer on the WWW without any restrictions. You agree to hold harmless and indemnify FAQS.ORG against any claims, costs, or damages resulting from publishing your answer.

 

FAQS.ORG makes no guarantees as to the accuracy of the posts. Each post is the personal opinion of the poster. These posts are not intended to substitute for medical, tax, legal, investment, accounting, or other professional advice. FAQS.ORG does not endorse any opinion or any product or service mentioned mentioned in these posts.

 

<< Back to: Objective-C FAQ


[ Home  |  FAQ-Related Q&As  |  General Q&As  |  Answered Questions ]

© 2008 FAQS.ORG. All rights reserved.