C array setting of array element value beyond size of array

后端 未结 3 433
孤独总比滥情好
孤独总比滥情好 2020-12-19 18:43

I Have this C code snippet

int numbers[4]={1};

numbers[0]=1; numbers[1]=2; numbers[3]=3; numbers[10]=4;
printf(\"numbers: %d %d %d %d %d %d\\n\",numbers[0],         


        
3条回答
  •  醉话见心
    2020-12-19 19:26

    It doesn't cause any errors because it is decayed to a pointer arithmetic.

    When you write numbers[10], it is just numbers + 10 * sizeof(numbers), which is fairly correct.

    It's undefined behavior to access memory you're not meant to (not allocated for you), so every index out of bound that you access is garbage, including 0.

    Accessing indexes greater than 4 will not increase the array's size, as you said, and additionally, it does not do anything either.

提交回复
热议问题