-2

I have this problem for CS. I'm using the code p3 = &s1[3]; however when I cout p3 it displays the value instead of the address. Is this to expected and the problem is right or is there something I am doing wrong?

Given the following declarations:

int i = 3, j, *p1 = &i, *p2;
char s1[20] = "Wow, more pointers!", *p3;

Write a statement that makes p3 equal to the address of the fourth element of s1.

  • my apologies I was typing fast I was already using the code p3 = &s1[3]; so it compiles fine the output is still the array of characters and I want it to be the address of that element alone – user4892930 Oct 11 '15 at 22:48
  • 1
    We don't care how fast you type, but we expect complete code that was tested before posting. We don't like to chase ghosts. – Karoly Horvath Oct 11 '15 at 22:57

5 Answers5

4

The << operator for streams has several overloads. One of them takes a char*, and prints a string (a sequence of chars starting from that address, until the next 0). A different one takes a void* (a pointer to anything), and prints the address it points to.

If you cast the pointer to void* yourself, it will force the compiler to choose the void* overload that prints the address:

cout << (void*)p3;

Your pointer assignment is not wrong; the problem is when you print it.

user253751
  • 57,427
  • 7
  • 48
  • 90
2

That's how std::cout treats (char*). This question contains comprehensive answer.

Community
  • 1
  • 1
Gerald Agapov
  • 210
  • 1
  • 10
0

By assigning to *p3 you are not modifying the pointer p3, you are modifying the memory that it points to. To modify the pointer p3 itself, just assign to p3.

Isabelle Newbie
  • 9,258
  • 1
  • 20
  • 32
0

The assignment asks you to make "p3 equal to the address of the fourth element of s1", but you're assigning the address to *p3, not to p3.

*p3 is what p3 points to. p3 is the address.

Btw your *p3 = &s1[3]; shouldn't even compile. If it does, enable your compiler warnings and errors.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
-1
p3 = s1+3;

Because the elements are at s1+0, s1+1, s1+2, s1+3, ...

Note that this is exactly equivalent to saying:

p3 = &s1[3];

... and some people who are uncomfortable with pointer arithmetic might prefer that. Personally I prefer the first version I gave.

cliffordheath
  • 2,536
  • 15
  • 16