-1

I have some code:

#include <iostream>
#include <string>
using namespace std;
int main(){
    char abc [20] = "Hello Hello Hi";
    char* ptr = abc;
    cout << (abc+3);
return 0;

}

Why does it print out from the third character up and not simply the third character?

-edit- to whoever flagged it down. it's not the same as prinf(), but same type of concept. i just didnt know the nuances

  • 3
    `cout << abc;` doesn´t print the first (0th) character only too, but the whole string... Skipping 3 bytes doesn´t change that behaviour. – deviantfan May 15 '15 at 01:14
  • 1
    Why have `char* ptr = abc` at all? – AndyG May 15 '15 at 01:15
  • possible duplicate of [printf() prints whole array](http://stackoverflow.com/questions/16962144/printf-prints-whole-array) – AndyG May 15 '15 at 01:20

3 Answers3

7

To understand why, you have to understand a bit of pointer arithmetic.

abc is the same as &abc[0] and (abc + 3) is the same as &abc[3]

that being said, cout prints a string from a given char * to a null character.

Therefore, you are basically just printing the string that starts at the third character to the end of the string. If you wanted to print just the third character, you could dereference the pointer to the third character like this.

 *(abc + 3)
Andrew Malta
  • 850
  • 5
  • 15
  • thanks @andrew-malta that makes sense. the only thing i didnt know was that it always prints a string from given char * to a nul char –  May 15 '15 at 01:22
4

char abc [20] decays to char*, which is effectively a c-style string. abc+3 remains a pointer, just offset from abc[0], so std::cout will still print it as a string.

AndyG
  • 39,700
  • 8
  • 109
  • 143
2

Because streams have an overload for char* that treats the input like a C-String. The stream operators will print everything until a null terminator (when presented with a char*).

If you want to print a single character then you have to convert your expression to be char not char*.

cout << (abc+3);     // Type of expression is char*

cout << (*(abc+3));  // Type of expression is char
                     // This prints a signle character.
Martin York
  • 257,169
  • 86
  • 333
  • 562