Shao Miller
7/1/2011 6:47:00 PM
On 7/1/2011 1:32 PM, Shao Miller wrote:
> On 7/1/2011 6:28 AM, Lauri Alanko wrote:
>> There are two ways to initialize a char array: with integer
>> expressions or with a string literal:
>>
>> char foo[3] = { 102, 111, 111 };
>> char bar[4] = "bar";
>>
>
> Hmmm...
>
>> However, I'd like to initialize the array so that its first element is
>> defined with a (constant) integer expression, and the rest of the
>> elements are defined with a string literal, i.e. something like:
>>
>> char baz[4] = { 3, "baz" };
>>
>> This is of course illegal. What I can do is:
>>
>> char* baz = (char*)&(struct {char i; char c[3]}){ 3, "baz"};
>>
>> But to my understanding there can be padding between i and c, so this
>> isn't fully portable. Is there a better way?
>
> It looks like you have C99, based on your "can do" with a compound
> literal. If you don't mind having roughly an equal amount of padding to
> your string literals, perhaps you could use something like:
>
#define M_DECL_STRING(id, string) \
char \
id ## _[2][sizeof string] = { \
{ [sizeof string - 1] = sizeof string }, \
{ string }, \
}, \
* id = id ## _[0] + sizeof string - 1
#include <stdio.h>
#define M_FOO_STR "foo"
#define M_BAR_STR "hum a few bars"
static M_DECL_STRING(foo, M_FOO_STR);
static M_DECL_STRING(bar, M_BAR_STR);
int main(void) {
char * i;
i = foo + 1;
printf("size: %d, chars: { ", foo[0]);
while (*i)
printf("'%c', ", *i++);
printf("'\\0' }\n");
i = bar + 1;
printf("size: %d, chars: { ", bar[0]);
while (*i)
printf("'%c', ", *i++);
printf("'\\0' }\n");
return 0;
}