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)



Welcome to the worst part of C.

The [] syntax is used for arrays. The * syntax is used for pointers. You can treat pointers and arrays the same way, most of the time, but not when declaring them. That's because when you are declaring an array, the compiler sets aside some space for the array's items. But when you are declaring a pointer, you don't get any extra space set aside. The pointer is just a place for you to store a memory address.

In other words,

// Sets aside space for one memory address. (Likely 4 or 8 bytes).
char *a;

// Sets aside space for an array of ten characters. (Likely 10 bytes).
char b[10];

// This is an error because the compiler doesn't know how much space to set aside.
char c[];

// If you say "b", the compiler will automatically return to you
// the memory address of b's first entry, so you can do this:
a = b;
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!