Hacker News new | ask | show | jobs
by burgerbrain 5469 days ago
If you're thinking of arrays as second class citizens, you're thinking of the language incorrectly. Rather you should realize there are no arrays, only pointers to chunks of memory and arithmetic operations.
3 comments

There are arrays. C defines types. When you declare a variable as an array of int, C knows that variable is of type "array of int" and treats that differently than if it had been declared as "array of pointers to int" or "array of char" or "pointer to array of pointers to pointers to int".

I spent many years believing it when people made exactly the assertion you have(see my other posts on this article), but it wasn't until I tried to build a C compiler myself how wrong it is to think of arrays this way. Yes, C gives you the power to reference memory in a more or less arbitrary way. That does not mean that the arrays you declare are not arrays.

You're wrong; there ARE arrays: make int a[16], *aa; and compare sizeof(a) with sizeof(aa). The confusion arises from the fact that the VALUE of an array is a pointer to its first element. When you consider that C is a pure pass-by-value language, everything fits nicely into place.
sizeof behavior is just icing over what is really going on. You might as well argue that arrays really exist because we have the [] operator.
No not really. What's really going on is that A has been declared as an array of 16 ints, while aa has been declared as a pointer to int. Those are different types, and C treats them differently sometimes (but not all times).
Aside from the additional information that the C compiler is capable of knowing about in the case of A, it is the same crap going on under the hood.
You're not writing in under-the-hood, though, you are writing in C. If you want to properly understand compiler warnings and errors you need to know that arrays and pointers are separate types.

Yes, "under the hood" it might be the same, but that's true of many languages if you dig deep enough. C is just a little closer. Yes, at one level a char declaration is just a smaller minimum memory allocation than int, but C will check both those types and if you want to use C properly you'll want to understand its typing and casting rules.

Well, QED.