I need to store two items per array element — two arrays of char, which might contain null bytes — and then still be able to use sizeof() to get their length. Since these values will not change during execution, I think GCC should be able to handle this.
Here’s the code:
#include <stdlib.h>
#include <stdio.h>
struct name_data {
char *name;
char *data;
} name_bins [] = {
{ "John", "\xAA\xAA\x00\xAA" },
{ "Mark", "\xFF\x0A\x00\x33\x01\x01\x03\x04\x04\x05" },
};
char bin_test[] = "\xFF\x0A\x00\x33\x01\x01\x03\x04\x04\x05";
int main () {
printf("sizeof(bin_test) = %lu\n", sizeof(bin_test));
printf("sizeof(name_bins[1].data) = %lu\n", sizeof(name_bins[1].data));
exit(0);
}
The output of this code is:
sizeof(bin_test) = 11
sizeof(name_bins[1].data) = 8
However, bin_test is equivalent to name_bins[1].data in content — although the type definition is different — bin_test is a char[] and names_bins[1].data is a char*.
Is there a way to define the name_bins array with char[]s instead?
Is there a way to force GCC to recognize this values as static constants and return the real content size with sizeof() — which it already calculates at compile time?
You can almost do what you want by storing the size of
dataas a separate entry:And then:
Then you’d just have to make sure your
name_binsinitialization was right. You could toss a macro in the mix to avoid repeating yourself though: