This is a question from a C language course. Someone wants to return a value from a function with a pointer. He assigns the pointer address to result_ptr and prints this pointer's value.
When there is no Line A, printf() works fine: printf() prints 3.
However, when another addition() function is called in front of the printf(), something wrong happens: the printf() prints 5.
If Line A is commented out and Line B, another printf() function, is uncommented: the printf() prints 0.
What exactly is going on?
int *addition(int a, int b) {
int d = a + b;
int *c = &d;
return c;
}
int main(int argc, const char * argv[])
{
int *result_ptr = addition(1, 2);
addition(2, 3); // Line A
// printf("Another line\n"); // Line B
printf("result = %d \n", *result_ptr);
return 0;
}