1 #include <stdio.h> 2 int main(void) { 3 unsigned short str[5+1]; 4 const unsigned short length = sizeof(str)/sizeof(str[0]); 5 unsigned short x; 6 7 printf("Значение length = %hu\n", length); /* выведет 6 */ 8 9 for(x=0; x<length-1; x++) 10 str[x] = x; 11 12 str[x+1] = 5; 13 14 printf("Значение length = %hu\n", length); /* выведет 5 */ 15 16 return 0; 17 } 

Prog is purely experimental. Question: why has the length changed? If you remove 12: then all the rules. How does the code in 12: affect the length? Or is it something else? Explain, please.

  • where do you write? in dev-c ++ both times 6 - mrexox
  • 3
    You access the array beyond its boundary. According to the rules of the language, it is impossible to do this , it starts undefined behavior. After that, all rules have the right to be canceled and have the right to happen anything: the constants will become variables, the read_file function read_file turn into format_disk , and dereferencing the pointer will send you to the police. Just never do that. - VladD
  • Alignment, register variables, optimization - many factors will give a variation in behavior even in the same compiler. - user6550

2 answers 2

Because it so happened that the variable length is on the stack immediately after str[5+1] . And the line that recorded outside the array is exactly this memory, writing a different value there.

  • @klopp Right. It should be str [x + 1] = 5; replace with str [x] = 5; Thank. - dr_kraken
  • one
    @dr_kraken, (deleted the previous comment because it read the code incorrectly) for (x = 0; x <length-1; x ++) str [x] = x; The cycle ends at the moment when the condition ceases to be fulfilled. in fact, this will happen when x reaches ( length - 1 ) - it will increment before the comparison, and after the comparison, the decision will be made whether to execute a code block or interrupt the loop. x + 1 will be equal in length , or in 6. - etki
  • In line 12, however, x+1 is 6 at this point. BTW, the error is "floating", it all depends solely on the compiler's goodwill, how it distributes local variables from memory (it can even be length and put them into registers, or and align the variables to many bytes => and the record will slip into nowhere, etc) - user6550

These are only assumptions, but:

  1. Set str
  2. Immediately after str, the length is set in memory.
  3. Immediately after str, in length + 1, it is written five. This value is occupied by length, and this memory is overwritten. Formally, no one touches the variable, so the compiler does not swear about this.
  • @Etki Nothing is written to length + 1. What are you speaking about? - dr_kraken
  • @dr_kraken see the comment under the @klopp answer. By length + 1 I, of course, meant "the last element of str + 1". - etki