Why this code is giving unexpected output.
int * func(int *xp)
{
int y = 10 + *xp;
return (&y);
}
void main()
{
int x = 10;
int *xp = func(&x);
printf("%d\n", x);
printf("%d\n", *xp);
}
expected output:
10
20
Real Output:
10
1074194112
You are returning a pointer to a variable (
y) that goes out of scope the moment you leavefunc. This is undefined behaviour.It is not entirely clear what you’re trying to achieve, but there are several ways to fix this:
intby value;*xpin place and don’t return anything;int*parameter and store the result in there (again returningvoid);mallocornewand return that (the caller would be responsible for correctly freeing that memory).It is impossible to say which of the above are applicable to your problem without knowing the broader context.
Lastly,
main()should returnint(thanks @pmg for spotting this). This is not related to the problem you’re having but is worthing pointing out.