1

I've downloaded a program which seems to have an error at the line:

for(i=0; i<SIZE_OF_DATA; i--){ 

in main.c, however as a newbie programmer I'm not too sure how to resolve it.

Here's main.c :

#include <stdio.h>
#include "util.h"

#define SIZE_OF_DATA 10

int main(void) {
    int data[SIZE_OF_DATA];

    generateRandomData(data, SIZE_OF_DATA);


    int i;
    for(i=0; i<SIZE_OF_DATA; i--){
        printf("%d: %d\n",i,data[i]);
    }

    return 0;
}
2
  • 3
    Change i-- to i++ in for(i=0; i<SIZE_OF_DATA; i--). Commented Mar 15, 2015 at 19:55
  • Did you actually run this and see printed i going down to negative values? I'd think that would be pretty clear indication of what's wrong... Commented Mar 15, 2015 at 20:19

3 Answers 3

4

Your problem is that you use i--. So the loop will count backwards, i.e. 0, -1, -2, -3 and so on and will always be smaller than SIZE OF DATA

The correct code would be

for(i=0; i<SIZE_OF_DATA; i++) {

Otherwise you'll have a perfect infinite loop :)

Sign up to request clarification or add additional context in comments.

2 Comments

INT_MIN - 1 is undefined behavior. So not necessarily an infinite loop. But possibly.
Yes, it will probably warp at -2147483648. But that hasn't much relevance here for understanding the problem.
2

You probably need

for(i=0; i<SIZE_OF_DATA; i++)

instead of

for(i=0; i<SIZE_OF_DATA; i--)

i-- means that the value of i will be 0 then -1,-2... which you dont want. SIZE_OF_DATA will be a positive value and hence the for loop will result in an infinite loop and hence your problem.

Comments

1

Choose any one

1.for(i=0; i<SIZE_OF_DATA; i++)

2.for(i=SIZE_OF_DATA -1 ; i>=0; i--)

1.You are starting your loop from 0 to SIZE_OF_DATA. Since you are progressing towards your size so you should increment your iterator i.

2.You are doing the opposite here ; i is set to the last position i.e SIZE_OF_DATA - 1 and now you have to decrement your iterator i till you reach 0.

Note In your code , you are starting from 0 and going towards negative side with i--. Your exit condition for for loop i<SIZE_OF_DATA will remain true always. This can cause you serious issues

1.Segmentation fault (accessing a negative index in the array data[] i.e data[i] and i is going towards negative integers).

2.Infinite loop as your termination condition will is always true. (It has to be false to come out of the loop).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.