I have an array of (pointers to) arrays of different lengths, which I learned I could define using compound literals:
const uint8_t *const minutes[] = {
(const uint8_t[]) {END},
(const uint8_t[]) {1, 2, 3, 4, 5 END},
(const uint8_t[]) {8, 9, END},
(const uint8_t[]) {10, 11, 12, END},
...
};
gcc accepts this just fine, but clang says: pointer is initialized by a temporary array, which will be destroyed at the end of the full-expression
. What does this mean? The code seems to be working, but then again, lots of things seem to work when they point to memory that's no longer allocated. Is this something I need to worry about? (Ultimately I only really need it to work with gcc.)
Update: Something fishy is going on. It says here that:
Compound literals yield lvalues. This means that you can take the address of a compound literal, which is the address of the unnamed object declared by the compound literal. As long as the compound literal does not have a const-qualified type, you can use the pointer to modify it.
`struct POINT *p; p = &(struct POINT) {1, 1};
This example code seems to be doing exactly what I'm trying to do: a pointer to something defined by a compound literal. So is the clang error message legitimate? Will this end up pointing to unallocated memory when compiled with either clang or gcc?
Update 2:
Found some documentation: "In C, a compound literal designates an unnamed object with static or automatic storage duration. In C++, a compound literal designates a temporary object, which only lives until the end of its full-expression." So it seems that clang is right to warn about this, and gcc probably ought to as well, but doesn't, even with -Wall -Wextra
.
I can't guess why a useful C feature was removed from C++, and no elegant alternative way of accomplishing the same thing was provided.