数组
数组是位于内存中的连续空间。
下图example[2]最终的值为6可以说明这一点(32位系统中char大小为4)
int example[5];
example[2] = 2;
int* ptr = example;
*(int*)((char*)ptr + 8) = 6;
两种声明方式,一种在栈,一个在堆。
int example[5];
int* another = new int[5];
生命周期不同,在栈只在作用域内有效,而在堆需要手动释放内存。
delete[] another;
在堆生命的数组不能获得数组的大小。example->size()会出错,可以通过一些小技巧,在声明数组的时候就将数组大小存储。
static const int exampleSize = 5;
int example[exampleSize];
另外提供了一个官方的array数组,边界检查,更为安全,性能会慢一点点。
#include <array>
std::array<int, 5> another;
another.size();
字符串
一个字节,默认ASCII编码
声明字符串的几种方式:
#include<iostream>
#include<string>
const char* baga = "helol";//新版本禁止把指针指向常量
char test[4] = {'H','e','l',0};
std::string name = "lhx";
std::string本质就是char数组和一些内置函数。
双引号字符串是常量不能相加。
void PrintString(std::string string) {
string += "h";
std::cout << string << std::endl;
//不会修改传进来的字符串,复制字符串很慢,只为了函数操作;
}
string+=“h”是因为库里将=重载才可以相加
优化:
void PrintString(const std::string& string) {
}
std::string name1 = std::string("lhx") + "hello";
name.size();//求大小
char test[4] = {'H','e','l',0};
strlen(test);//c语言库函数