Hacker News new | ask | show | jobs
by robertelder 3705 days ago
Here are the relevant parts of the C standard:

C89 3.3.3.4

"The sizeof operator... When applied to an operand that has array type, the result is the total number of bytes in the array."

C89 3.2.2.1

"Except when it is the operand of the sizeof operator or the unary & operator, or is a character string literal used to initialize an array of character type, or is a wide string literal used to initialize an array with element type compatible with wchar_t, an lvalue that has type ``array of type '' is converted to an expression that has type ``pointer to type '' that points to the initial member of the array object and is not an lvalue."

Additionally, here is a thread of Linus Torvalds pointing out even more of the confusing nature of arrays and sizeof in C:

https://lkml.org/lkml/2015/9/3/428

2 comments

Additionally, here is a thread of Linus Torvalds pointing out even more of the confusing nature of arrays and sizeof in C:

I really like the idiom for passing sized arrays suggested at the end of that LKML thread[1]: pass them by reference!

  void func(int (*arr)[256])
  {
    printf("arr size: %ld\n", sizeof(*arr));
  }

  int main(void)
  {
    int array[256];
    func(&array);
  }
[1] https://lkml.org/lkml/2015/9/7/147
I doubt Torvalds telling everyone that sizeof was a function helped with this confusion.