-1

An obvious example of such metadata is the number of elements the array contains. Things like sizeof(array) and &array + 1 work accordingly, so a C program clearly must have some way of knowing how many elements an array holds. How and where is this information stored?

Anthony
  • 409
  • 1
  • 5
  • 10
  • 1
    It is stored in the type. `int arr[] = {4,4,4}` is an `int[3]`. It's a distinct type. – Raildex May 11 '21 at 10:00
  • 2
    If you for some reason want to know exactly how some compiler is built up internally, then many of them are open source. – Lundin May 11 '21 at 10:02
  • @JulianH I'm not the one asking the question. For beginners, it would probably tell them not to worry about such things, but I have no idea how experienced the OP is. – Lundin May 11 '21 at 10:16
  • According to the design C is a language where you don't pay for something you don't want as is C++. Therefore you can be sure that the C language attempts to minimize runtime overhead. As a matter of fact no array metadata is maintained at runtime despite you design your own array wrapper. All array size calculations are performed at compile time. – Wör Du Schnaffzig May 11 '21 at 10:20
  • The compiler knows the types of expressions. The size of `int[5]` is no more mysterious than the size of `int` – M.M May 11 '21 at 11:20
  • @Lundin I am a complete beginner. – Anthony May 11 '21 at 12:41
  • @Anthony Okay then don't worry about how the compiler does things internally :) – Lundin May 11 '21 at 13:29
  • @Lundin Lol. I can't help it sometimes. Too curious. – Anthony May 12 '21 at 14:06

1 Answers1

2

In C, both cases are taken care of by the compiler, which knows the size of the array, but this information is not kept after compilation, and cannot be used in runtime.

i.e. sizeof() is calculated and replaced with the actual size during compilation, it's not a real function call

For example:

The following code:

static int arr[] = {1, 2, 3};

int foo() {
    return sizeof(arr);
}

Is compiled to:

0000000100003f60 _foo:
100003f60: 55               pushq   %rbp
100003f61: 48 89 e5         movq    %rsp, %rbp
100003f64: b8 0c 00 00 00   movl    $12, %eax ; << 12 is sizeof(arr)
100003f69: 5d               popq    %rbp
100003f6a: c3               retq
100003f6b: 0f 1f 44 00 00   nopl    (%rax,%rax)
MByD
  • 135,866
  • 28
  • 264
  • 277
  • This answer doesn't explain `char x[rand() % 6 + 1];` and then outputting `sizeof x` – M.M May 11 '21 at 11:21
  • @M.M: In this case `x` is a variable length array, so `sizeof x` has to be evaluated at runtime. How and where that size information is stored is up to the individual compiler. – John Bode May 11 '21 at 12:46