-2

I thought when you define an empty array like this char t[2000] = ""; it would set all elements of that array to 0, but when I create a 2000 size array, the 2000th element is not 0. Same thing with 3000 size array, but other sizes like 100, contain all zeroes.

Why aren't all the elements 0?

#include <stdio.h>

int main() {
    char t[2000] = "";

    for (int i; i <= 2000; i++) {
        if (t[i] != 0) {
            printf("\n\nt[%i] is not 0\n\n\n", i);
        }
        printf("t[%i] = %i\n", i, t[i]);
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189

2 Answers2

2

A 2000 element array only has legal indices from 0 to 1999 inclusive. Accessing t[2000] is outside the array, invoking undefined behavior. It's not part of the array, it could contain anything (or just make demons fly out of your nose, whatever). This is why typical C for loops run until i < arraylength, not until i <= arraylength; you must exclude the length itself as an index.

Note that you have a second bit of undefined behavior when you fail to initialize i in the first place; you really need to do:

for(int i = 0; i < 2000; i++)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

Your array only has elements from t[0] to t[1999]. When you try to access elements beyond that, you are going beyond the bounds of array and this results in undefined behavior.

When you try to access the element t[2000], you are not guaranteed about what its value might be.

  • It might store an value that was previously assigned to it sometime, might give you an runtime error or any other error. This cannot be determined and hence is called as undefined behavior.

  • It might just seem to work fine and give the expected value without giving any errors(C doesn't check array boundaries).

  • It might give you a value but not the one you expected but some previously stored value.

So, remember that whenever we loop an array or string of size s, always use the condition - for(int i = 0 ; i < s ; i++) and not i<=s which will result in illegal access of t[2000]. You never know what result it might produce.

Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32