0

I was hoping someone could tell me why my int variable is getting set to 0 after running the for loop in the following simple C program. It seems to me that the loop should have nothing to do with my variable named "breakPoint" in the code below?

#include<stdio.h>

#define MAX 100

int main(){
    char line[MAX];  //array to use for something

    int breakPoint = 23;

    printf("breakPoint is %d \n\n", breakPoint); //breakPoint prints out as 23

    /* intialize the array */
    for(int i = MAX; i>0; --i)
        line[i]=0;

    printf("breakPoint is now  %d\n\n", breakPoint); //breakPoint now prints out as 0???

    getch();
    return 0;
}

Thanks much, I appreciate it.

I suspect that I'm declaring the array to be one size (i.e. MAX) and then when I run the for loop I try to set each element and my indexing is off. I found that when I start the for loop index at MAX-1 instead of MAX, the problem goes away, i.e. the variable breakPoint is left unchanged.

/* intialize the array this way fixes the problem */
for(int i = MAX-1; i>0; --i)
    line[i]=0;

but still could someone explain to me why this is happening? Especially, why would messing with my character array affect a completely different variable? whats the link?

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60

1 Answers1

3

Your array, char[MAX], contains MAX elements. Since the counts start at 0 in C, that means an array that had 5 elements would have the indexes 0, 1, 2, 3, and 4. Similarly, your array of MAX elements will go from 0 to MAX - 1. However, your for loop started with i = MAX. Since MAX is greater than MAX - 1, your access went past the bounds of the array.

Doing such a thing is undefined behavior, which means that technically, anything can happen. The program may crash. You may clobber some other memory in the program. You may open up a wormhole to a parallel dimension, causing an invasion of evil space goats that raid your sock drawer, eating one out of every pair of your socks so that you wonder why your socks keep going missing. Pretty much anything goes.

Anyway, in this case, what happened was that you overwrote the value of your int variable.

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60