Here is a function(returnArr) to read 10 integers and store them in an array. increment each by 2, and return the array base address. Using the base address, the array elements are printed (in three()).
#include<stdio.h>
#include<stdlib.h>
int* returnArr()
{
int arr[10];
size_t iter = 0;
while( iter < 10 )
{
scanf("%i",arr+iter);
arr[iter]+=2;
printf("%i ",arr[iter]);
iter+=1;
}
return arr;
}
void three()
{
size_t iter = 0;
int* arr = returnArr();
//putchar('\n');
while( iter < 10 )
{
printf("%i ",arr[iter]);
iter+=1;
}
return;
}
int main()
{
//one();
//two();
three();
return 0;
}
Ideally the program should print garbage values since the address points to the location of a local variable in another function which was called before the array traversal.
But it is actually printing the array elements when the putchar function call is commented, garbage values when the getchar function call is included in the program code.
Using gcc 4.7.2 on Debian.
Can anyone explain this ?
-Newbie