Arrays and pointers don't behave the same because they're not the same at all, it just seems that way.
Arrays are a group of contiguous items while a pointer is ... well ... a pointer to a single item.
That single item being pointed to may well be the first in an array so that you can access the others as well, but the pointer itself neither knows nor cares about that.
The reason that arrays and pointers often seem to be identical is that, in many cases, an array will decay to a pointer to the first element of that array.
One of the places this happens is in function calls. When you pass an array to a function, it decays into a pointer. That's why things like the size of an array don't pass through to the function explicitly. By that I mean:
#include <stdio.h>
static void fn (char plugh[]) {
printf ("size = %d
", sizeof(plugh)); // will give char* size (4 for me).
}
int main (void) {
char xyzzy[10];
printf ("size = %d
", sizeof(xyzzy)); // will give 10.
fn (xyzzy);
return 0;
}
The other thing you'll find is that, while you can plugh++
and plugh--
to your hearts content (as long as you don't dereference outside of the array), you can't do that with the array xyzzy
.
In your two structures, there's a major difference. In the pointer version, you have a fixed size pointer inside the structure, which will point to an item outside of the structure.
That's why it takes up space - your 8-byte pointer is aligned to an 8-byte boundary as follows:
+----------------+
| 1 char variable|
+----------------+
| 7 char padding |
+----------------+
| 8 char pointer |
+----------------+
With the "unbounded" array, you have it inside the structure and you can make it as big as you want - you just have to allocate enough memory when you create the variable. By default (ie, according to the sizeof
), the size is zero:
+----------------+
| 1 char variable|
+----------------+
| 0 char array |
+----------------+
But you can allocate more space, for example:
typedef struct {
char whatever;
char my_array_square[];
} my_struct_square;
my_struct_square twisty = malloc (sizeof (my_struct_square) + 10);
gives you a variable twisty
which has a whatever
character and an array of ten characters called my_array_square
.
These unbounded arrays can only appear at the end of a structure and there can be only one (otherwise the compiler would have no idea where these variable length section began and ended) and they're specifically to allow arbitrarily sized arrays at the end of structures.