数组
int main() {
int example[2];
int* ptr = example; // 不会出错,因为数组本质上就是指针
example[1] = 5; // 内存中00 00 00 00 05 00 00 00
*(ptr + 1) = 6; // 内存中00 00 00 00 06 00 00 00, 偏移量取决于type
*(int*)((char*)ptr + 4) = 6; // 和上面的效果是一样的
int* another = new int[5]; // 另一种初始化方式,这样another存储的就是地址而不是实际的值,使用new了就需要使用delete删除
std::array<int, 5> another; // 在C++11里也可以这样初始化,它提供了size()的方法
}
字符串
void PrintName(const std::string& string) { // 通常字符串穿参需要确保不变性,const关键字,不复制性,&关键字
std::cout << string << std::endl;
}
int main() {
char* name = "zhubin"; // 双引号代表字符串,在内存中以00结尾
name[2] = 'c';
char name2[6] = {'z','h','u','b','i','n'}; // 这个print会打印很多,因为他后面没有00结尾
char name2[7] = {'z','h','u','b','i','n', 0}; // 这样就不会报错
std::string name = "zhubin";
std::string name = "zhubin" + "hello"; // 会报错,字符串本质是字符数组指针,指针不能和指针相加
std::string name = std::string("zhubin") + "hello";
name += "hello";
}