Following are two code snippets. One worked correctly but the other failed.
Main Function
int main
{
int *x,*y,n,*c;
//some code
c=myfunc(x,y,n);
//rest code
}
Here is the code that worked:
int * myfunc(int *a, int *b, int n)
{
int *s,i,*t;
for(i=0;i<n;i++)
s[i]=x[i]+y[i];
t=s;
return s;
}
And here is the code that doesn't work
int * myfunc(int *a, int *b, int n)
{
int s[100],i,*t;
for(i=0;i<n;i++)
s[i]=x[i]+y[i];
t=&s[0];
return t;
}
What happens here is that even though the returned value is the correct address(tested and checked) the contents seemed to get modified on its own. However this did not seem to be the case in the first scenario.
Not only that but the entire array of s[100]
has different contents at the end of the executed query. Which basically means the contents of all these addresses are getting modified because of some random reason.
The compiler used was Turbo C.
EDIT
Question in Straight forward terms:
Why does the contents of s when initialized as s[100]
get reset after returning and where as contents of s when initialized as *s does not reset. Please note: I Have Not used malloc() or functions that has anything to do with stacks anywhere on my code.