Is const char * distinct from other pointers?

So, I recently iterated over pointers and links because they are constantly used in resources that I used to learn OpenGL. I noticed that the pointer const char *seems to behave slightly different than other pointers. To demonstrate, I created this test program:

#include <iostream>

int main() {

    int i = 2; 
    int *pi;
    //const char c = "hello world"; 
    const char *pc = "hello world";

    pi = &i;

    std::cout << "'hello world' type is " << typeid("hello world").name() << std::endl;

    std::cout << "pi is " << pi << std::endl;
    std::cout << "*pi is " << *pi << std::endl;

    std::cout << "pc is " << pc << std::endl;
    std::cout << "*pc is " << *pc << std::endl;



    return 0;
}

output:

'hello world' type is char const [12]
pi is 0079FC38
*pi is 2
pc is hello world
*pc is h

. -, const char c = "hello world" ; ? , , , "hello world", char const [12]. , . , , int (pi). pc hello world, ? ( ) , *pc , ?

+4
4

, const char * , .

, ++ ( ) const char * , . , operator<<().

const char *, ASSUMED char ( , "Hello World", ) char .

void * (.. ). void *.

, const char * , . , ++ const char * - ( , ).

. , ,

std::cout << "pi is " << (void *)pi << std::endl;
std::cout << "pc is " << (void *)pc << std::endl;

(.. , ), operator<<().

+3

char * ( ) " ", , '\0' ( std::string, "" ) ). , cout , char *, , . () , , , char int.

+1

const char c = "hello world" ; ? , , "hello world", char const [12]

. int int const[12].

pc , ?

std::cout std::ostream, std::basic_ostream, operator<< void const*:

http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt ( 7)

, void const*. int*.

char const* , std::basic_ostream non-member operator<< char*, :

http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2

- operator<< char const* , .

, , char const* , .

, *pc , ?

*pc char, , operator<<.

operator<< char& char, , ; std::cout << 'X'; undefined.

, :

#include <iostream>

int main()
{
    char c = 'X';
    char cc = 'Y'; // for more astonishing effect in practice, especially
                   // when compiled without optimisation

    std::cout << &c; // undefined behaviour
}

; . , std::cout << "Hello world"; .

0

. , .

.

const char c = "hello world". c char, , , - string ( ). , .

-,

*piwill give you the value of the variable that it points to pi, but in the case it char *will *pcgive the value of the first character in the character string (this means that in "hello world" it *pcpoints to the first character in the string).

If you do pc[1], it will give you the second character in the character string, but will pcindicate the entire string.

0
source

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


All Articles