Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How is it possible to save two data in the same memory location on C?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading