0

Does the = (assignment) get me a copy of the content or points me to the same location in memory? For some reason, I end up thinking that what the code does is not setting y = 44 in a separate memory location but rather point to x

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int x = 1;
    int y = 44;

    // Print Address and Value of x
    printf("%p\n",&x);
    printf("%i\n",x);

    // Print Address and Value of y
    printf("%p\n",&y);
    printf("%i\n",y);

    y = x;

    // Add Separator
    printf("------------------\n");

    printf("%p\n",&x);
    printf("%p\n",&y);

    if (x==y)
    {
        printf("YES\n");
    }
}
WHICH gives me the following on the command line

0x7fff5a5e8cb8 
1 
0x7fff5a5e8cb4 
44
------------------ 
0x7fff5a5e8cb8 
0x7fff5a5e8cb4 
YES

EDIT: I am noting a different behavior with Python. Once I set y=a I am getting the same memory location. When updating y I expected a to also change but that doesn't happen.

enter image description here

1

[EDIT: This applies to programming in the C language. See comments and question edit.]

The = operator copies values from one place to another. It matters what type of vars are being used.

That code does exactly what you said, `y=x;' takes the value stored in x and stores a copy of it in y. It does NOT change the address that y points to.

However, if x and y were (address) pointers instead of int variables, it would have copied the address stored in x and would have stored it in y. In this case, both address pointers would be pointing at the same memory location.

Confused yet? ;-)

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Thanks, Cliff for the response. What you said makes sense. However, I did a quick example in Python and saw something unexpected to me. When setting y=a I am getting the same memory location. However, when updating y, a doesn't change. I thought it would change. May 26 at 2:02
  • Not surprising. FIrst, my answer applied to programming in C, where var typing is far more strict. Welcome to the wonderful world of languages with different standards! Python does things very, very differently. For example, you can have arrays with different types in python, while c requires all elements to be the same type. You just need to remember what language you're in. You also have an excellent grasp of how to test behavior you don't fully understand. I still find myself doing the same kind of things! Well done!
    – Cliff B
    May 26 at 2:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .