Home > Enterprise >  How could it print value of the block excessing the size of Array?
How could it print value of the block excessing the size of Array?

Time:07-06

[enter image description here][1]First of all I declared array of 5 elements.

int a[5];

And then I assign 58 to a[8] which is for experiment.

After I tried to print the value of a[8].I was shocked when I viewed the output as 58.

I feel its ok may be compiler allocated memory dynamically and so I wanna test with sizeof(a).The output was 20(5*4) then I be like hmm??

Check the demo program and of course my image too.

#include<stdio.h>
 int main()
{
    int a[5];
    a[8]=58;
    printf("\t a8=%d snd size of A= %d",a[8],sizeof(a));
}

The output was a8=58 snd size of A= 20

Note the fact that I practice the same with char and of course on different devices.

Ultimately when I tried to assign 58 to a[15] or increasing index then the output was 0 all the cases.enter image description here

CodePudding user response:

"And then I assign 58 to a[8] which is for experiment." And with that experiment you enter the dark realm of "undefined behaviour". All bets are off. Whatever your experiments show as result - you can ignore it. Read up on "nasal demons".

If you get a result which seems to indicate that accessing beyond the array somehow worked - then you can ignore that result. It is undefined behaviour and you did not find out anything, especially not that your compiler does some magic beyond what is promised with the array definition.

CodePudding user response:

It is something like you book for 5 rooms in a hotel and try to access room number 8. It is lucky that this room is not use by any one so you could enter the room. However, if all the rooms are full, some complain (undesired behavior) will come. :)

CodePudding user response:

A simple example of slightly modified code around your example:

#include<stdio.h>
int main()
{
    int x = 23;
    int y = 24;
    int z = 25;
    int a[5];
    int p = 15;
    int q = 16;
    int r = 17;
    a[8]=58;
    printf("\t a8=%d snd size of A= %zd\n",a[8],sizeof(a));
    printf("\t x=%d, y=%d, z=%d, p=%d, q=%d, r=%d\n", x, y, z, p, q, r);
}

Before you try to compile and run this. What is your expected result?

  • Related