As a non-C/C++ expert I always considered square brackets and pointers arrays as equal.
ie :
char *my_array_star;
char my_array_square[];
But I noticed that when use in a structure/class they don't behave the same :
typedef struct {
char whatever;
char *my_array_star;
} my_struct_star;
typedef struct {
char whatever;
char my_array_square[];
} my_struct_square;
The line below displays 16, whatever
takes 1 byte, my_array_pointer
takes 8 bytes.
Due to the padding the total structure size is 16.
printf("my_struct_star: %li
",sizeof(my_struct_star));
The line below displays 1, whatever
takes 1 byte, my_array_pointer
isn't taken in account.
printf("my_struct_square: %li
",sizeof(my_struct_square));
By playing around I noticed that square brackets are used as extra space in the structure
my_struct_square *i=malloc(2);
i->whatever='A';
i->my_array_square[0]='B';
the line blow displays A:
printf("i[0]=%c
",((char*)i)[0]);
the line blow displays B:
printf("i[1]=%c
",((char*)i)[1]);
So I cannot say anymore that square brackets are equals to pointers. But I'd like to understand the reason of that behavior. I'm afraid of missing a key concept of that languages.
See Question&Answers more detail:os