在阅读书籍c++ primr plus时,产生疑问字符串是通过指向首个字符处的指针使用,字符同样可以由指向字符的指针使用,这两者之间有什么区别,编译器又是如何区分?
#include <typeinfo>
#include <iostream>
int main()
{
char h = 'H';
char *p = &h;
char c[] = "Hello World";
std::cout << p << std::endl;
std::cout << "Type of h is: " << typeid(h).name() << std::endl;
std::cout << "Type of c is: " << typeid(c).name() << std::endl;
p = c;
std::cout << p << std::endl;
return 0;
}
输出结果:
H��_
Type of h is: c
Type of c is: A12_c
Hello World
对输出结果的一些思考:
1,cout会将指向字符的指针当成是指向字符串第一个字符的指针使用,因此会导致输出结果第一行的乱发,输出H后继续输出接下来内存空间中的数据,直到碰到数据中等于'\0'的字节。
2,指向字符串的指针和指向字符的指针类型不同,A12_c的含义A代表数组,12代表长度,c代表字符指针。