我正在使用一个不错的 GCC 扩展,它允许我们在结构中声明 VLA。现在我找到了一种通过这种方式将 VLA 传递给函数(按值)的方法。我还找到了一种返回方法,但在非常有限的情况下。
这个例子的功能代码是这样的:
extern void func3()
{
size_t size;
scanf("%zu", &size);
struct tx{int _[size];} fn()
{
struct tx rt;
for(size_t i=0; i < size; ++i)
scanf("%d", &rt._[i]);
return rt;
}
volatile __typeof__(fn) *pf = fn;
}
上面的例子是为测试目的而设计的(特别是为了比较它编译的二进制代码)。
然而,这是非常有限的,因为返回数组的大小在函数的不同调用之间没有变化。
我怎样才能使返回的数组大小等于函数参数之一或此函数中的某个其他局部参数。
我认为alloca
在这种情况下对我没有帮助,因为它分配的内存在函数退出(IRC)处立即被销毁。
我想写这样的东西:
/*???*/ func5()
{
size_t size;
scanf("%zu", &size);
struct {int _[size];} rt;
for(size_t i=0; i < size; ++i)
scanf("%d", &rt._[i]);
return rt; //ok - return the structure
}
换句话说,问号内的类型可能是什么?或者也许还有其他解决方案(但不使用malloc
)?
这种函数的理论用法理论上需要另一种类型来存储返回值,因为调用者无法获得返回结构的大小(除非有办法避免这种情况?)。但乍一看它应该是这样的:
size_t size;
//scanf("%zu", &size);
struct {int _[size];} tmp; //create locally VM type
//compatible with the one
//returned by our theoretical func5
//we can't directly initialize tmp here (gcc complains)
tmp = ((__typeof__(tmp) (*)())func5)(); //direct assignment between VM structures
//works here on the other hand
//as function return value is rvalue and we can't
//take its pointer and cast it to our local VM structure type
//we instead cast the function pointer
如果我们这样做:
__typeof__(func5()) tmp = func5();
它不起作用,因为 VM 返回类型func5
将取决于它的参数或局部变量。然而,目前这一切都是理论上的,因为我们仍然无法定义这个函数。