-1

so if i run this code it will give the expected answer of 9

int main()
{
    int a[]={9,8,7,6,5,4,3,2,1};
    int n=sizeof(a)/sizeof(a[0]); printf("%d", n);
}

but if i change sizeof(a[0]) to sizeof(&a[0])..then the output is 4 Why does this happen? Exactly what does the computer 'think' when it is given sizeof(&a[0])?

piku_baba
  • 59
  • 7
  • 2
    `a[0]` is an `int`, therefore `&a[0]` is a *pointer* to `int` (e.g. a pointer to the first element of `a`) So, `sizeof(&a[0])` is what? `sizeof (a_pointer)`. – David C. Rankin Dec 01 '18 at 06:42
  • 1
    so this means that it is returning the number of bytes of an int pointer, right? – piku_baba Dec 01 '18 at 06:45
  • 3
    Yep -- you got it (8-bytes on x86_64 or 4-bytes on x86) If the `"a pointer"` is confusing (you had to name the array `a`...) it is simply `sizeof (pointer)` – David C. Rankin Dec 01 '18 at 06:45
  • `&anything` gets the variable's pointer, whatever type this variable is. All pointers have the same size (8 bytes for 64-bit architecture, 4 bytes for 32-bit). – Havenard Dec 01 '18 at 07:01
  • 1
    @Havenard See https://stackoverflow.com/questions/1241205/are-all-data-pointers-the-same-size-in-one-platform-for-all-data-types – Support Ukraine Dec 01 '18 at 07:04
  • @4386427 I know, but, while it is technically true, it's only the case on some microcontrollers where you don't even get a real ANSI C compiler. It's not even worth taking this random factoid in consideration for 99.99% of applications. – Havenard Dec 01 '18 at 07:09

1 Answers1

2

&a[0] on an array a in C yields the address of its first element. On a 16-bit system, sizeof of that address is most likely 2, on a 32-bit system, sizeof that address it is 4, and, on a 64-bit system, it is 8.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Krassi Em
  • 182
  • 8