I’m learning C language, specifically pointers and I have this little question.
How is it possible to save two data in the same memory location on C? Look my code:
#include <stdio.h>
int main()
{
const int y = 2;
int *const ptr_y = &y;
*ptr_y = 4;
//Values
printf("%d\n", y);
printf("%d\n\n", *ptr_y);
//Memory locations
printf("%p\n", &y);
printf("%p\n", ptr_y);
return (0);
}
OUTPUT:
2
4
0x7ffeeb501788
0x7ffeeb501788
OUTPUT I EXPECT:
4
4
0x7ffeeb501788
0x7ffeeb501788
I would like to know how this code works internally.
IMPORTANT: I am aware that the constant pointer is not correctly declared (const int *ptr_y).
>Solution :
You are not saving the data in two different locations, it’s the same location.
y is stored somewhere on the stack, that location has an address, ptr_y is a pointer and it contains that same memory address because you assigned it using address-of operator &:
int *const ptr_y = &y;
When you dereference ptr_y using * operator you are accessing the address stored in ptr_y which incidentally is the address of y, so it’s the same memory address, you are just accessing it in two different ways.
*ptr_y = 4 invokes undefined behavior because you cannot change the contents of a const variable.