There is a claim that this code right here would not return the correct "Sum" because of the preceding PrintHelloWorld()
being executed and displacing the value that the pointer *ptr
points to. However, I get the correct value each time I run it and even ran the PrintHelloWorld()
function a dozen or more times right before the printing of *ptr
.
So why is my code working and returning the value even though the pointer is pointing to a value that's been popped off the stack as claimed?
#include <stdio.h>
#include <stdlib.h>
void PrintHelloWorld()
{
printf("Hello World\n");
}
int *Add(int *a, int *b)
{
int c = (*a) + (*b);
return &c;
}
int main()
{
int a = 2, b = 4;
int *ptr = Add(&a,&b);
PrintHelloWorld();
printf("Sum = %d\n", *ptr);
return 0;
}