0

Here is my code:

#include<stdio.h>
int main()
{
int i, list[1];
list[0]=1;
list[1]=2;
list[2]=7;
list[55]=70;
i=sizeof list;
printf("%d %d %d %d %d Size of array is %d",list[0],list[1],list[2],list[3],list[55],i);
return(0);
}

It returns "1 2 7 4 70 Size of array is 4". Why can i assign, say 55 to list[55]. list[55] should not exist as I only gave the array list enough memory for 1 integer, right? In addition shouldn't this give me an error as list[3] doesn't exist? and if for some reason i am changing the size of the array why isn't the size 56? It comes out as 4.

So what is happening to give me the output i got?<--{main question}

[As i don't want to create a separate thread for a related question, why when i code int list[0]; the program crashes, if i am somehow changing the size from 1 to 4 shouldn't I be able to change the size from 0 to 4?] Thanks for your help, I know this probably a stupid or obvious question.

  • 2
    C has no guard rails. It's not stopping you from doing things you shouldn't. You're overwriting some other memory space that you shouldn't be. – matmo Oct 19 '17 at 18:28
  • It's better if you do create separate "threads" for related questions. That being said, the kind of thing you're doing has been addressed by many questions on SO. Have a look at some of those linked in the sidebar (on the right) and you may find your answer. – David Z Oct 19 '17 at 18:29
  • 1
    You are declaring an int array of 1 element, the size of the array is 4, which is the total amount of bytes the array occupies. – MikeJ Oct 19 '17 at 19:24

0 Answers0