0

Here I have declared an integer array of size 2 but I am able assign more than 2 elements to the array and also print them but the array size is indicated as of size 8bytes before and also after assigning a value to it.

int main()
{
    int a[2];
    printf("size is %d\n",sizeof(a));
    a[0]=1;
    a[1]=2;
    a[2]=3;
    a[3]=4;
    a[4]=5;
    printf("%d %d %d %d\n",a[0],a[1],a[2],a[3],a[4]);
    printf("size is %d\n",sizeof(a));
}

Output

size is 8
1 2 3 4
size is 8

So is it possible to assign more elements than the specified size to an array? If yes is it only applicable if you declare the array in this fashion and can this be applied to any type of array in c?

Ak_and.co
  • 11
  • 3
  • 2
    As you showed yourself it is possible but that leads to undefined behavior.:) – Vlad from Moscow Jun 11 '21 at 19:52
  • If you were expecting an error message when you tried this, your expectation was inaccurate. You often don't get an error message, but that doesn't mean it's okay. – Steve Summit Jun 11 '21 at 22:05
  • See also [this answer](https://stackoverflow.com/questions/57247807/difference-in-storage-of-memory-in-string-and-an-integer-array-in-c-after-using/57252388#57252388), which is talking more specifically about strings, but the lessons are the same for any kind of array. – Steve Summit Jun 11 '21 at 22:11

0 Answers0