Alice is writing a simple program to practice the use of pointers. She uses the function
add() to calculate the sum of two integers. Instead of returning the value, the function
returns a pointer to the result.
#include <stdio.h>
int *add(int a, int b) {
int c = a + b;
int *d = &c;
return d;
}
int main() {
int *result = add(1, 2);
printf("result = %d\n", *result);
printf("result = %d\n", *result);
}
Surprisingly, Alice notices that if she prints the result for the second time, the result is
wrong! So she turns to you for help.
(1) Can you explain what's happening here?
(2) Alice insists that add() should return a pointer. Can you propose a way to fix it?