0

I'm just trying to understand the difference in how you output pointers.

let's say I have:

int x = 100; int*p = &x; 

what would each of the following do?

cout << p << endl; cout << *p << endl; cout << &p << endl; 
5
  • 1
    Why not ask the compiler? Commented Apr 3, 2014 at 19:08
  • Looks like a homework or test question. Commented Apr 3, 2014 at 19:09
  • @TiagoRodrigues, just compiling and running can tell you a lot, especially using the sizeof function. Commented Apr 3, 2014 at 19:14
  • 1
    If it is a hardware type of company, I would be surprised if this kind of question is asked. The C++ questions may not even occur. Expect MATLAB or LabVIEW oriented questions though. If you know Verilog, VHDL, and/or SystemVerilog, I can see questions about them occurring too. Commented Apr 3, 2014 at 19:17
  • They do some programming too. Mostly scripting though. This is just in case a pointer question comes up. Commented Apr 3, 2014 at 19:18

2 Answers 2

3
cout << p << endl; // prints the adress p points to, // that is the address of x in memory cout << *p << endl; // prints the value of object pointed to by p, // that is the value of x cout << &p << endl; // prints the address of the pointer itself 
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't say how this will be printed but what it does
@lizusek: Was not a criticism, just wanted to add that info.
3

int*p = &x; creates a pointer, p, which points to the variable x. A pointer is actually implemented as a variable which holds the memory address which it is pointing to. In this case, you will get the following. For the purposes of this example, assume that x is stored at 0x1000 and p is stored at 0x1004:

  • cout << p << endl; will print the address of x (0x1000).
  • cout << *p << endl; will dereference the pointer, and hence will print the value of x (100).
  • cout << &p << endl; takes the address of p. Remember that pointers are simply variables in their own right. For this reason, it will print 0x1004.

3 Comments

Note that the address of x is not always 0x1000, the size and value of the pointer varies by system. Sames goes for &p, size and value varies.
+1 if you fix the implication that the addresses are somehow predictable
@LightnessRacesinOrbit better?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.