4

When I run the code below my output is not what I expect.

My way of understanding it is that ptr points to the address of the first element of the Str array. I think ptr + 5 should lead to the + 5th element which is f. So the output should only display f and not both fg.

Why is it showing fg? Does it have to do with how cout displays an array?

#include <iostream>
using namespace std;

int main()
{
    char *ptr;
    char Str[] = "abcdefg";

    ptr = Str;
    ptr += 5;

    cout << ptr;

    return 0;
}

Expected output: f

Actual output: fg

2
  • 3
    ptr - pointer to string. If you want to print char, use *ptr: cout << *ptr; Commented Jan 17, 2016 at 21:46
  • Replace "lead" with more appropriate "point to" and you'll get the idea. Commented Jan 17, 2016 at 21:52

2 Answers 2

6

When you declare:

char Str[] = "abcdefg"

The string abcdefg is stored implicitly with an extra character \0 which marks the end of the string.

So, when you cout a char* the output will be all the characters stored where the char * points and all the characters stored in consecutive memory locations after the char* until a \0 character is encountered at one of the memory locations! Since, \0 character is after g in your example hence 2 characters are printed.

In case you only want to print the current character, you shall do this ::

cout << *ptr;
Sign up to request clarification or add additional context in comments.

Comments

2

Why is it showing fg?

The reason why std::cout << char* prints the string till the end instead of a single char of the string is , because std::cout treats a char * as a pointer to the first character of a C-style string and prints it as such.1

Your array:

char Str[] = "abcdefg";

gets implicitly assigned an '\0'at the end and it is treated as a C-style string.

Does it have to do with how std::cout displays an array?

This has to do with how std::cout handles C-style strings, to test this change the array type to int and see the difference, i.e. it will print a single element.


1. This is because in C there are no string types and strings are manipulated through pointers of type char, indicating the beginning and termination character: '\0', indicating the end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.