2

Memory addresses specify how many bytes of data they point to in memory, so it seems that the size of any variable is determined by looking at the memory address and seeing how much the variable occupies in memory. So how is the size of an array determined??? - because an array is a pointer to only the first item in the array by default:

int main() {
    int a[] = {1,2,3,4,5};
    // both show same memory address
    printf("%p\n", a);
    printf("%p\n", &a[0]);
    // somehow the entire size of a is calculated
    printf("%lu\n", sizeof(a)); // 20 (all elements)
    return 0;
}

1 Answers1

3

When you write

int a[] = {1,2,3,4,5};

The compiler already knows "a" will only have 5 ints in it.

When you call

sizeof(a)

You compiler (not your program) will calculate the size of a. This basically sets the number "20" in your program. Everytime your program runs, it'll output the number 20, it won't use sizeof. This is not evaluated at runtime, this is evaluated at compile time, since in your case sizeof is a compile time operator. (To be noted sizeof can be evaluated at runtime when you have variable length arrays)

Sam
  • 794
  • 1
  • 7
  • 26
  • not 100% the truth. Some time ago `sizeof` was evaluated compile time and everything was easy. Now in the era of VLAs sizeof can be also calculated dynamically runtime - for example `int foo(int x) { int y[x]; printf("%zu\n", sizeof(y)); }` – 0___________ Jan 26 '20 at 21:50
  • good catch, my answer was mostly in the context of the question. I edited to reflect your comment. Thanks for the correction – Sam Jan 26 '20 at 21:57