Values ​​past a valid C-Style string pointer

I am currently going through a "C ++ Primer". In one of the questions of the exercise, he asks:

What does the following program do?

const char ca[] = { 'h', 'e', 'l', 'l', 'o' };

const char *cp = ca;

while (*cp)
{
    cout << *cp << endl;

    cp++;
}

I am very glad that I understand that * cp will continue to be the last character of the ca [] array, because there is no null character in the last element of the array.

This is more for my own curiosity about what makes the while loop false. It seems like 19 characters are always displayed on my computer. 0-4 - the welcome line, 5-11 are always the same, and 12-19 change with each execution.

#include <iostream>

using namespace std;

int main( )
{
    const char ca[ ] = { 'h', 'e', 'l', 'l', 'o'/*, '\0'*/ };

    const char *cp = ca;

    int count = 0;

    while ( *cp )
    {
        // {counter} {object-pointed-to} {number-equivalent}
        cout << count << "\t" << *cp << "\t" << (int)*cp << endl;

        count++;
        cp++;
    }

    return 0;
}

Question: what causes the while-loop to become invalid? Why are 5-11 always the same character?

+4
4

, , undefined, , , , "".

, , :

|H|e|l|l|o|XXX|____cp___|__count__|

XXX - " ", 8. - - , 0, ( )

cp - "H", . .

, .

() 8 ( , , - x86), , :

  • "Hello"
  • ( yare - )
  • cp ( , main , )
  • ( )

"0" , .

, , , , , , .

+1

++ ca[0] ca[4], . (.. *) ca[0] ca[4]; , ca[4], . , , undefined. .

, , : - , . - . .

. . 5..20 cp count, . , , , int , 4. , - , -.

+3

, Undefined behavior. , , , , .

"" 5-11 , , .

+1

:

: ( ), \0:

const char ca[] = "hello";

. initializer-list

const char ca[] = { 'h', 'e', 'l', 'l', 'o' };

, :

const int ib[] = {2, 5, 7, 9};

, .


const char ca[] = { 'h', 'e', 'l', 'l', 'o' };
const char *cp = ca;
while (*cp){
    cout << *cp << endl;
    cp++;
}

Undefined , , \0.

, while-loop ?

, , , undefined (), , 0 , .

5-11 ?

, : , ; ; -, , , .


Footnote: Your program may call other functions before int main(). (it is not your business what he calls). These functions initialize static variables, which include things likestd::cout

0
source

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


All Articles