Eric Sosman
4/23/2011 6:32:00 PM
On 4/23/2011 2:10 PM, pozz wrote:
> If I want to define a constant string array I could do:
> const char *strarr[] = {
> "First string",
> "Second string",
> "Third string",
> };
> The compiler automatically define a constant string for each element of
> the array and put a char pointer to that string in the array.
Yes (for suitable interpretations of "constant"). But that's not
a property of the array initialization; it's the way the compiler deals
with string literals: The literal initializes an anonymous array and
serves as a stand-in for that nameless array's name. The rest follows
from the usual array-to-pointer conversion.
> Is it possible to get a similar thing for integer arrays?
> struct mystruct {
> size_t array_len;
> int intarr[];
As written, this won't work at all, even without trying to
initialize. Ask your compiler's opinion if you don't believe me.
> void *ptr;
> };
> struct mystruct myarr[] = {
> { 3, { 1, 2, 3 }, NULL },
> { 5, { 5, 7, 1, 3, 0 }, NULL },
> ...
> };
>
> Actually I can do only this:
> const int arr1[] = { 1, 2, 3 };
> const int arr2[] = { 5, 7, 1, 3, 0 };
> ...
> struct mystruct myarr[] = {
> { SIZEARR(arr1), arr1, NULL },
> { SIZEARR(arr2), arr2, NULL },
> ...
> };
>
> Of course, it's annoying to define each array I'll never use directly.
> Actually I can do only this:
> const int arr1[] = { 1, 2, 3 };
> const int arr2[] = { 5, 7, 1, 3, 0 };
> ...
> struct mystruct myarr[] = {
> { SIZEARR(arr1), arr1, NULL },
> { SIZEARR(arr2), arr2, NULL },
> ...
> };
>
> Of course, it's annoying to define each array I'll never use directly.
This works, if you change the struct element to an `int*'. Since
there's no construct to create an anonymous array of int, as there is
for creating arrays of char, you must give each array a name.
Somebody may suggest a hack along the lines of
struct mystruct myarr[] = {
{ 3, (int*)"\1\0\0\0\2\0\0\0\3\0\0", NULL },
{ 5, (int*)"\5\0\0\0\7\0\0\0\1\0\0\0\3\0\0\0\0\0\0", NULL },
};
Pay no attention to anyone who makes such a suggestion. The person
who suggests such a thing is devious and possibly clever, but not wise.
--
Eric Sosman
esosman@ieee-dot-org.invalid