数组表示一类数据的集合
#include<iostream> int main() { int example[5]; int *ptr = example; for (int i = 0; i < 5; ++i) { example[i] = 2; } example[2] = 5; *((int*)((char*)ptr + 8)) = 6; std::cin.get(); }
在强制类型转换那一行代码加上断点进行调试,输入首地址example查看内存
可以看到四个字节为一组,组成了数组example的内存地址
按下f10后发现example[2]中的值改变了
因为char是字符类型,一个字节(byte),int整型4字节,所以将整型指针ptr进行强制类型转换,转换成字符型时,想要访问原来数组的第三个元素,就要在首地址的基础上向后移动2个int大小的空间,也就是8个char的空间,然后再强转回int进行赋值。
#include<iostream> int main() { int example[5];//在栈上建立 int *another = new int[5];//在堆上建立,生命周期不同上面数组,需要用delete删除 delete[] another; std::cin.get(); }
以内存的方式来看这两种方法的不同,new int[5];这种方式更像是间接存储,example直接就是数组首地址,但是another不是,another是一个指针,指向后面申请的五个连续内存地址的首地址。
#include<iostream> class Entity { public: int example[5]; Entity() { for (int i = 0; i < 5; i++) { example[i] = 2; } } }; int main() { Entity e; std::cin.get(); }
此时输入"&e"可以直接看到内存中的数组,所有的值经过构造函数都赋值为2
用new来新建数组
#include<iostream> class Entity { public: int *example=new int[5]; Entity() { for (int i = 0; i < 5; i++) { example[i] = 2; } } }; int main() { Entity e; std::cin.get(); }
进入调试,输入&e来查看内存,发现内存中存储的并不是5个2,而是一串地址
这就是example中存储的,new新申请的五个内存空间的首地址,输入这个地址进行查看,看到了new int[5]中存储的5个2
数组长度不可以是变量,只能使用常量,要让编译器直到这是一个不可变的值,c++11中可以使用标准数组类型(array)类型来定义数组
#include<iostream> #include<array> class Entity { public: static const int exampleSize = 5; int example[exampleSize]; std::array<int,5> another;//c++11 Entity() { for (int i = 0; i < another.size(); i++) { another[i] = 2; } } }; int main() { Entity e; std::cin.get(); }