I'm trying to do something like this:
struct SomeStruct {
const char *bytes;
const char *desc;
};
SomeStruct example = { { 0x10, 0x11, 0x12, 0x13 }, "10-13" };
Why isn't this working?
I'm trying to do something like this:
struct SomeStruct {
const char *bytes;
const char *desc;
};
SomeStruct example = { { 0x10, 0x11, 0x12, 0x13 }, "10-13" };
Why isn't this working?
Probably because { 0x10, 0x11, 0x12, 0x13 }
is an array of char
, not a pointer to char
.
Try SomeStruct example = { "\x10\x11\x12\x13", "10-13" };
instead.
Because the { ... }
syntax is only suitable for assigning arrays, whereas const char*
is a pointer, not an array.
If you declare bytes
as an array instead – char bytes[4];
– the assignment will work.
Because the compiler cannot convert {1, 2, 3, 4}
to a pointer to bytes (it can convert "10-13" to a pointer to char).
You can specify the bytes in 'string' format (if you don't mind an extra 0x00 in the memory pointed to by bytes
):
SomeStruct example = {"\x10\x11\x12\x13", "10-13"};
As others have said, your initializer sequence is valid for an array, and the struct contains a pointer. You can use maraguida's response, using a string literal, but IMHO, this isn't the most readable (and it won't work if, say, you decide to replace the explicit constants with manifest constants). The more general solution is to define a separate, named array, and use it:
char const structBytes10to13[] = { 0x10, 0x11, 0x12, 0x13 };
SomeStruct example = { structBytes10to13, "10-13" };
This will work for arbitrary initialization expressions in the character array.