Arithmetic of pointers on arrays

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

My way of understanding what ptrpoints to the address of the first element of the array Str. I think that ptr + 5should lead to the + 5th element, which is equal f. Thus, the output should only be displayed f, not both fg.

Why is he showing fg? Is this due to how coutthe array is displayed?

#include <iostream>
using namespace std;

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

    ptr = Str;
    ptr += 5;

    cout << ptr;

    return 0;
}

Expected Result: f

Actual output: fg

+4
source share
2 answers

When you declare:

char Str[] = "abcdefg"

The string is abcdefgsaved implicitly with an extra character \0that marks the end of the string.

, cout a char*, , , char * , char*, , \0 ! \0 g , , 2 .

, :

cout << *ptr;
+6

fg?

, std::cout << char* , char , std::cout char * C . 1

:

char Str[] = "abcdefg";

'\0' C.

, std::cout ?

, std::cout C, int , .


1. , C , char, : '\0', .

+2

Source: https://habr.com/ru/post/1624698/


All Articles