C99 变长数组维基百科示例

发布于 2024-12-23 02:14:03 字数 285 浏览 1 评论 0原文

我在维基百科上看到了这个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

已下线请稍等 2024-12-30 02:14:03

指针尚未过期。它是指向有效内存的指针,直到函数 read_and_process 结束。这意味着当调用进程时它仍然是定义的。

这是无效使用的示例:

float read_and_process(int n)
{
    float vals[n];

    for (int i = 0; i < n; i++)
        vals[i] = read_val();
    return vals;
}

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:

float read_and_process(int n)
{
    float vals[n];

    for (int i = 0; i < n; i++)
        vals[i] = read_val();
    return vals;
}
雅心素梦 2024-12-30 02:14:03

不要忘记,包含所有 read_and_process() 自动变量(包括 float vals[n])的堆栈帧在以下情况下仍然有效并位于内存中: >process() 被执行。

Don't forget that the stack frame that contains all of read_and_process()'s automatic variables, including float vals[n], is still valid and in memory when process() is executed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文