是否有可能在复合语句中使用alloca? 例子:alloca内部复合语句
typedef struct
{
size_t len;
char* data;
} string_t;
#define str_to_cstr(str) \
({ \
char* v = alloca(str.len + 1); \
v[len] = 0; \
memcpy(v, str.data, str.len); \
})
// ... and somewhere in deep space
int main()
{
string_t s = {4, "test"};
printf("%s\n", str_to_cstr(s));
return 0;
}
从我的经验效果很好,但我不知道它是安全的。 BTW,它用gcc 4.8.4
'v [len]'typo .. – BLUEPIXY
...无论是,还是'memcpy(v,str.data,str.len + 1);' –
虽然你建议应该工作,为什么不只是维护一个'.data'结尾的空字符并使用它(可能强制转换为'const char *')? – Dmitri