29 comments

[ 4.3 ms ] story [ 51.0 ms ] thread
In practice, the [static n] notation can give you useful warnings and bounds checking.

https://godbolt.org/z/PzcjW4zKK

And while the (*array_ptr)[3] notation take a moment to get used to, it is very logical. If you have a pointer to an array, you dereference it first and then indx into it. Again, useful for bounds checking: https://godbolt.org/z/ao1so9KP7

I know of this notations but I don't see many people using [static n].

Not sure why, maybe it doesn't feel like C anymore, maybe it feels hacky?

typically if you're passed an array you'd want to get more anyway, so you'd get passed a struct. Not sure.

The parentheses in (*parray)[i] would be unnecessary if dereferencing used postfix notation.

  Current:       All postfix

  *ptr[3]        ptr[3]*   // indexed access, then deref

  (*ptr)[3]      ptr*[3]   // deref, then indexed access*
Dereferencing does have a postfix notation, so you can try it (sort of):

    #define $ [0]
then you can say ptr $[0] or ptr[0]$ and see if it's really better...
there's no array type in c
There is a big difference between:

struct A { int size; char data[]; }

struct B { int size; char *data; }

This is one of the things that I feel is an inappropriate abstraction that is around for historical reasons. When I do FFI to call C from rust, I usually wrap the generated API (Which is pointer based) into rust's &[] array syntax. Arrays/lists/Vecs etc in most non-C languages feel like an abstraction over a collection of items; I feel like C's exposing the pointer directly is taking a low-level memory/MMIO operation and inserting it into business logic. Conceptually, I like to keep them separate; pointers for writing drivers, accessing registers, writing to flash memory etc. Arrays/lists/vecs for higher level operations on collections.

Tangent: I have a pet theory that part of Zig's raison d'etre is to fix some of the problems with C, while accommodating its pointer-based data structures, and the resulting patterns.

[flagged]
Because half the world revolves around C fundamentals, sadly enough. Things would be a lot better if there existed a non-C portable way to share libraries across language boundaries (including libC).
There is a history to it; in one of the predecessor languages, like B, Ritchie actually had arrays that had a hidden pointer to their start. The "array to pointer decay" was actually a real operation that loaded an address from memory, and it was possible to twiddle the bits to relocate an array. One problem with it was no way to initialize such a pointer field that would allow an array to live in dynamically allocated storage (no constructors in the language).

So in short, the bad design (array values produce pointers) was informed by conceptual compability with an earlier design in which that was literally happening.

C array types are weird because C doesn't really need arrays. It's not what C was about.

But if you designed a language in the era where Fortran, THE array language, reigned supreme, nobody would use your language. The mindshare Fortran had is difficult to convey now, half a century later.

Think of it like making a chatbot today and not mentioning AI or LLMs, that's what making a language without arrays would have felt like in 1970.

> C array types are weird because C doesn't really need arrays. It's not what C was about.

I would phrase that differently: "The main feature of arrays (performing the `base + index * size` address computation) is already provided by the C pointer type via the `ptr[N]` syntax sugar, so having a separate array type might have felt redundant at the time".

I think having "proper" array types in a language (where the type carries both the array item type and the comptime length) only really makes sense when there's also a slice type (e.g. a runtime ptr/length pair). And I guess at any point during C's development this was a too big language change for the committee to swallow.

this exactly. if you need arrays or sequences of objects/memory items u can trivially implement them :/. why does it need to be embedded in the language?? people want the language to do all the programming for them. I suppose this is why they like LLMs too..

they should pay programmers less. get rid of all these moneygrabs

It still cracks me up that 3[x] and x[3] mean the same thing in C.
The real lack is that C doesn't have slices. Slices can do most of what pointers into arrays can do, with sane semantics. Slices were invented surprisingly late. They were implementable in the 1970s, but didn't really show up until the 1990s. Now that we have slices, the demand for pointers into the middle of an array has much decreased.

I had a go at retrofitting C with slices over a decade ago.[1] Too much political hassle.

[1] https://www.animats.com/papers/languages/safearraysforc43.pd...

Interestingly the article doesn't mention two-dimensional arrays and they're curios because they bring a certain asymmetry with them. It always tripped me over the most in C because I otherwise find the language very "symmetrical". It often feels like in design of this language the beauty of expressing certain things took priority over readability or safety which I admire in a way. But somehow not in the case of the two-dimensional arrays.

If you see a[i][j] it could mean two completely different things:

1) "a" is a continuous chunk of memory of N*M bytes, so it behaves as char*; a[i][j] == *(a + i*M + j)

2) "a" is an array of char* pointers that point to N completely distinct memory chunks of size M, so it behaves as char**; a[i][j] == *(*(a + i) + j)

With flat arrays the difference between an array as a variable and a pointer to the first element is literally negligible because you won't even see the difference in the assembly. This is why the automatic decay-to-pointer makes a lot of sense.

But that breaks completely with multiple dimensions. You definitely see the difference in the assembly because the memory layout is so different.

(comment deleted)
And just in case you have not come across this, C++ allows you you overload all the relevant operators here: [], *, ->

So, you really can't tell what's going on behind the scenes.

I wanted to pull my hair out seeing some 'enterprise' code use

  state[i] = foo;
for some kind of logging where i was the severity level. There were even instances of state[i++], where the severity was incremental. I hope someone has rewritten that codebase with AI by now.
> If you see a[i][j] it could mean two completely different things:

> 1) ... a[i][j] == *((char*)a + i*M + j) // I added the char* cast to make it correct

> 2) ... a[i][j] == *(*(a + i) + j)

You may already understand this but: even in case (1), you still have

   a[i][j] = *(*(a + i) + j)
(It has to - that's what operator[] means in C.)

It's just that, in this case, `a + i` is applying pointer arithmetic to char[M]* so it adds M * i bytes to a's address.

This is similar to how `a + i`, if a is int32_t*, will give you an address 4 * i bytes bigger than a.

Really the confusing part of this is that *(a + i), which is an array value i.e. has type char[M], decays to char* when you add an integer to it (or dereference it). This is a pretty crazy hack really. Imagine if, in C++, you could do this

   std::vector<int> v = {1, 2, 3};
   int* x = v + 1;   // equivalent to &v[1]
Yuck.
For 1), you can just write (&a[i])[j] .
From the title, I thought they were going to point out that `a[2]` and `2[a]` have identical meaning in C.
It's still weird to me that you can declare an array with the register keyword.

Then it (understandably) becomes UB to attempt to get the pointer.

(It also probably isn't stored in a register, since the keyword is just asking the compiler nicely.)

int x[n] and int *x are very different things when it comes to defining memory layout tho. In one case you end up with n int sized slots of memory, in the second with one register sized slot. That makes all the difference when defining structs for example.
C's array decay into pointers still catches me off guard sometimes. It is definitely one of those quirks you just have to memorize.
The way C handles array decay to pointers always trips up beginners, but it's exactly what makes passing data around so lightweight. Good writeup on a classic quirk.
But remember, C is simple.