Hi guys! Programming question:

In C, is an array _exactly_ the same thing as a pointer to the first element of the array? How does the program know the size of the array? Where is this information stored?

I just found out the difference between the length of a string and the size of the buffer reserved for that string. But if `char s[]` and `char *s` are the same thing, who controls the size of that?

(boost appreciated)


@camelo003 And here's an English explanation instead of code.

char s[] and char *s are both unsized.

char s[10] is sized. The compiler knows its size, but it doesn't store the size anywhere for your running program to look up later! After all, storing the size would cost a whole extra word of memory, and C thinks it's still the year 1975, so that kind of overhead is not acceptable! (cries)

So the C run-time doesn't give you array bounds checking. The C compiler might be able to perform some primitive bounds-checks on your char s[10], but any code that accepts a user-supplied offset (known only at runtime) won't be automatically checked.

Does that help at all? It's super hard to explain this stuff in a way that makes sense to people who don't already know it.

@camelo003 Finally, other C programmers feel free to correct any errors that I made here.

Sign in to participate in the conversation
OldBytes Space - Mastodon

The social network of the future: No ads, no corporate surveillance, ethical design, and decentralization! Own your data with Mastodon!