I'm actually going through some of the example code that demonstrates pointers in Kamran Amani's book, Extreme C. I edited the example and produced the code seen below:
#include <stdio.h>
#include <stdlib.h>
int* create_an_integer(int value){
int* var = (int*)malloc(sizeof(int));
printf("Memory Address of value: %p\n", &value);
var = &value;
printf("Memory Address of var: %p\n", var);
printf("Value at Memory Address of var: %d\n", *var);
return var;
}
int main(void) {
int* ptr = create_an_integer(3);
printf("\n\n");
printf("Memory Address of ptr: %p\n", ptr);
printf("Value at the memory address returned: %d\n", *ptr);
free(ptr);
return EXIT_SUCCESS;
}
When the code is executing and tries to display the memory address of ptr and the value at said memory address of ptr, it will correctly display the memory address but then will not show the correct value. However, the funny thing is that if I omit the line printf("Memory Address of ptr: %p\n", ptr);
, rebuild the code, and run it again, it correctly shows the value at the memory address in ptr, which in this case should be 3. Any help would be appreciated.