When I want to store dynamic array of data in a C structure, there are two ways to write it:
typedef struct {
int row;
int col;
char* data;
} item1;
Or
typedef struct {
int row;
int col;
char data[];
} item2;
Both of them will work. But they got some differences on my 64bit Mac OSX, with gcc Apple LLVM version 5.1 (clang-503.0.38):
sizeof(item1) is 16
sizeof(item2) is 8
Why is the difference? And, what else are different for the two implementations?
The full testing code is:
#include <stdio.h>
typedef struct {
int row;
int col;
char* data;
} item1;
typedef struct {
int row;
int col;
char data[];
} item2;
int main() {
printf("%d %d\n", sizeof(item1), sizeof(item2));
return 0;
}
The output is:
16 8
Size of pointer is machine specific (whether it is 32-bit or 64-bit). The result would be 12
and 8
bytes respectively on 32 bit machine. For 64-bit machine, answer would be 16
and 8
bytes.
See the explanation
typedef struct {
int row; // 4 bytes
int col; // 4 bytes
char* data; // 4/8 bytes on 32/64-bit machine
}item1 ;
Total size = 12/16 bytes on 32/64 bit machine.
typedef struct {
int row; // 4 bytes
int col; // 4 bytes
char data[]; // 0 bytes --> Flexible array
}item2 ;
Total size = 8 bytes.
Why size of flexible array is 0
?
[...] In particular, the size of the structure is as if the flexible array member were omitted [...]