从函数返回可变长度数组 [英] Returning a variable length array from a function

查看:173
本文介绍了从函数返回可变长度数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下函数递增"将1加到以数组表示的数字上.

The following function "increment" add 1 to a number represented as an array.

int*  increment(int array[], int size, int *sizeLen)
{
    int temp[size+1];

    int carry = 0;
    carry = (array[size-1]+1)/10;
    temp[size] = (array[size-1]+1)%10;

    for(int i=size-2;i>=0;i--)
    {
        temp[i+1] = (array[i] + carry)%10;
        carry = (array[i]+carry)/10;
    }
    if(carry)
    {
        temp[0] = 1;
        *sizeLen = size+1;
        return temp;
    }
    else
    {
        *sizeLen = size;
        return (temp+1);
    }
}

int main()
{
    int array[] = {9,9,9};
    int length;
    int *res = increment(array, sizeof(array)/sizeof(int), &length);
    for(int i=0;i<length;i++)
    {
        cout << res[i] << " ";
    }
}

我知道gcc支持可变长度数组并且它们已存储在堆栈上. 我希望一旦此函数结束,temp就会超出范围,并且尝试在main中打印数组应该会打印垃圾值. 但在我的情况下,将打印实际值. 函数中声明的可变长度数组何时超出范围?

I know gcc supports variable length arrays and they are stored on stack. I expect temp to go out of scope once this function ends and the attempt to print the array in main should print garbage values. But in my case the actual values are printed. When does the variable length array declared in the function goes out of scope?

推荐答案

此处的关键确实是数组的存储持续时间.它具有自动存储期限.具有自动存储期限的变量的生命周期在退出它们所在的作用域时终止.

The key here is indeed the storage duration of the array. It has automatic storage duration. The lifetime of variables with automatic storage duration ends the moment the scope they're are in is exited.

它完全符合您的期望.但是C语言中没有什么阻止您获取本地对象的地址并从函数中返回它.

It does exactly as you expect. But nothing in C stops you from taking the address of a local object and returning it from the function.

使用该指针是未定义的行为.它可能看起来有效,但是该数组对于所有意图和目的仍然是死的".这种指针俗称悬空指针".

Using that pointer is undefined behavior. It may appear to work, but the array is still for all intents and purposes "dead". Such pointers are known colloquially as "dangling pointers".

好吧,以上对于C都是正确的.由于这是关于GCC扩展名的,因此多数情况相同,但可能需要加一点盐.

Well, the above is true for C. Since this is about the GCC extension, the same applies mostly, but may need to be taken with a grain of salt.

这篇关于从函数返回可变长度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆