0

I'm newbie to C. And studying about Array. tutor says the number in the bracket defines the memory size allowed to the array.

for example, if I define array like

int luckyNumbers[10]

this array can't swallow more than 10 elements. However, it swallows more than 10, although it still says its size as 10.

here's what i've done

int main()
{
    int luckyNumbers[10];
    size_t n = sizeof(luckyNumbers)/sizeof(int);
    printf("%d\n", n);  // "10"

    luckyNumbers[1] = 80;
    luckyNumbers[2] = 80;
    luckyNumbers[3] = 80;
    luckyNumbers[4] = 80;
    luckyNumbers[5] = 80;
    luckyNumbers[6] = 80;
    luckyNumbers[7] = 80;
    luckyNumbers[8] = 80;
    luckyNumbers[9] = 80;
    luckyNumbers[10] = 80;
    luckyNumbers[11] = 80;
    luckyNumbers[12] = 90;

    printf("%d\n", luckyNumbers[12]); // "90". working right
    size_t n2 = sizeof(luckyNumbers) / sizeof(int); 
    printf("%d", n2);                     //still "10". why not 12?

    return 0;
}
yubin
  • 125
  • 8
  • 1
    `sizeof` tells you how big the array is, not how much you've stored in it. Also C doesn't check for array overflow. – Steve Summit Jan 20 '21 at 15:26
  • 3
    You've just discovered what all the fuss is about [buffer overflows](https://en.wikipedia.org/wiki/Buffer_overflow) in C. Your program might appear to still work. – Andrew Henle Jan 20 '21 at 15:27
  • 1
    In short, this is *undefined behavior*. It might seem to work, it might crash, it might reformat your hard disk, it might create a space-time rift and devour our solar system. – Fred Larson Jan 20 '21 at 15:29
  • 1
    "`n2` is still `10`". In C you can't expand an array by writing beyond its bounds. – Weather Vane Jan 20 '21 at 15:30
  • 1
    The array hasn't grown to accommodate the new elements, you've just written past the end of the array and clobbered any objects in memory after it. C doesn't require the implementation to do any bounds checking on array accesses. As long as you don't overwrite anything "important" your code will appear to function normally. You declared the array to be 10 elements wide, and that's what `sizeof` is reporting. – John Bode Jan 20 '21 at 15:30

0 Answers0