MHKz
MHKz

Reputation: 11

Why the two code snippets below give different answer in C++ from pointer perspective

why these two codes give different answers for the address of two variable a and b?

Code 1)

int *a, *b;
*a=1;
*b=2;
cout << *a << " in " << a << endl << *b << " in " << b << endl;
*b = *a;
cout << *a << " in " << a << endl << *b << " in " << b << endl;

Code 2)

int a=1, b=2;
cout << a << " in " << &a << endl << b << " in " << &b <<endl;
b = a;
cout << a << " in " << &a << endl << b << " in " << &b <<endl;

thanks.

Upvotes: 0

Views: 97

Answers (1)

Blaze
Blaze

Reputation: 16876

int *a, *b;
*a=1;
*b=2;

Here you are making two new pointers without initializing them, and then you write to where they point at. This is undefined behaviour and that might crash your program, or do even worse things, such as causing memory corruption that might be hard to debug.

Instead, try this:

int *a = new int, *b = new int;

That initializes the appropriate amount of memory on the heap and assigns the addresses to the pointers, making it safe to use the pointers like that.

*b = *a;

Here you're assigning the value of where a points at to where b points at. So both memory loactions should now store 1 (assuming the undefined behavior didn't crash the program yet).

int a=1, b=2;
cout << a << " in " << &a << endl << b << " in " << &b <<endl;
b = a;
cout << a << " in " << &a << endl << b << " in " << &b <<endl;

Here you have two ints on the stack. They both have different addresses, although they are usually not far apart (they probably have a difference of 4 or so). The values are as you would expect, a is 1 and b is 2 the first time around, then both of them are 1.

why these two cods gives different answers for address of two variable a and b

The first time it's an uninitialized value, oftentimes a value that was already in the memory and simply hasn't been cleaned up. Accessing it is undefined behavior either way.

The second time the values refer to valid memory on the stack. That's why the values printed are so different.

Upvotes: 4

Related Questions