Hani Goc Hani Goc - 1 year ago 70
C++ Question

How do you explain *(y_ptr)&val;

Problem description

I the following example I wrote the
*x_ptr = *(y_ptr)&val;
I can't understand why the output is
. What happened in the memory? I can't understand this combination.

// Example program
#include <iostream>
#include <string>

int main()
int *x_ptr, *y_ptr;
int val = 10;
y_ptr = &val;
*x_ptr = *(y_ptr)&val;

std::cout << *x_ptr << std::endl;

Suppose that I change
*x_ptr = *(y_ptr)&val
x_ptr = *(y_ptr)&val
the compiler will give the following error why?

10:20: error: invalid conversion from 'int' to 'int*' [-fpermissive]

Answer Source

The output is 10 because any number bit-AND-ed with itself stays unchanged.

What the expression does is simple: it dereferences y_ptr, which points to val, and bitwise-ANDs the result with the same val.

Note: you need to initialize x_ptr to some location to avoid a potential crash from dereferencing an uninitialized pointer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download