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] << " ";
}
}
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?