Search code examples
carrayspointersgarbage

Does nth index of n sized C array contain size of it?


I've written a C program for showing the values of an array using pointer. Here's the code :

#include <stdio.h>

int main()
{
    int a[] = {1, 1, 1, 1, 1};
    int *ptr = a;
    for (int i = 0 ; i < 5; i++)
        printf("%d ", *ptr++);
    printf("%d", *ptr);
}

As you can see after terminating the loop, the pointer holds the memory address of a value out of the array. As it i.e. the last output is not initialized, it should be a garbage value. But, every time it is showing 5 which is the size of the array. Then, I thought the next memory address of allocated memory for array contains the size of array. But, this is not happening with double type array.

Output for int array : 1 1 1 1 1 5
Output for double array : 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 0.000000 

Will anyone explain the output?


Solution

  • What you do invokes Undefined Behavior.

    It's simple a coincidence and probably just the value of i, print the address of i and check. But be careful, it will not always be that way. Just declare a new variable in the program and it might change.

    In the case of double it doesn't work because the address after the array no longer matches the address of i. It's what I mean when I say Be careful.