C99 变长数组维基百科示例
我在维基百科上看到了这个 C99 可变长度数组的示例:
float read_and_process(int n)
{
float vals[n];
for (int i = 0; i < n; i++)
vals[i] = read_val();
return process(vals, n);
}
这是不正确的吗?我的印象是,可变长度数组仍然只是指针,这意味着上面的代码将过期的指针 vals 传递给 process(...) 函数。
I came across this example of C99 Variable-length arrays on Wikipedia:
float read_and_process(int n)
{
float vals[n];
for (int i = 0; i < n; i++)
vals[i] = read_val();
return process(vals, n);
}
Is this incorrect? I was under the impression that variable-length arrays are still just pointers which means the above code is passing the expired pointer vals to the process(...) function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
指针尚未过期。它是指向有效内存的指针,直到函数 read_and_process 结束。这意味着当调用进程时它仍然是定义的。
这是无效使用的示例:
The pointer hasn't expired. It is a pointer to valid memory until the end of the function read_and_process. Which means it is still defined when process is called.
This would be an example of invalid usage:
不要忘记,包含所有
read_and_process()
自动变量(包括float vals[n]
)的堆栈帧在以下情况下仍然有效并位于内存中: >process() 被执行。Don't forget that the stack frame that contains all of
read_and_process()
's automatic variables, includingfloat vals[n]
, is still valid and in memory whenprocess()
is executed.