动态数组
序言:
数组类型变量有三个限制:
1)数组长度固定不变
2)在编译时必须知道其长度
3)数组只能在定义他的语句块内存在
与数组变量不同:动态分配的数组将一直存在直到程序显示的释放他!
正文:
1、每个程序在执行时都占用一块可用的内存空间,用于存放动态分配的对象,此内存空间称为程序的自由存储区,或堆(heap),在C++中使用new和delete在自由存储区中分配存储空间。
new表达式返回指向新分配数组的第一个元素的指针:
- //数组的维数可以是任意复杂的表达式
- int *pia = new int[10];
2、在自由存储区中创建的数组对象是没有名字的,只能通过其地址间接访问堆中的对象。
3、动态分配数组时,如果数组类型具有类类型,将调用该类的默认构造函数实现初始化;如果数组元素是内置类型,则无初始化:
- string *psa = new string[10];
- int *pia = new int[10];
4、可以跟在数组长度后面的一对空圆括号,对数组元素进行值初始化。
但是对于动态分配的数组,只能初始化为元素的默认值,不能像数组变量一样...
- int *pi = new int[10]();
5、const对象的动态数组
- const int *pci_bad = new const int[10]; //ERROR
- const int *pci_ok = new const int[10]();//OK
在实际应用中其实没有太大用处...
6、动态空间的释放
动态分配的内存到最后必须进行释放,否则,内存最终将会耗尽。如果不再需要使用动态创建的数组,则必须显式的将所占用的存储空间返还给程序的自由存储空间!
- delete []pia; //不要忘记了[],即使忘记了,编译器也不会发现...
7、动态数组的使用
通常就是在编译时无法知道数组的维数,所以才使用动态数组!
- const char *errno = "success";
- const char *errinfo = "Error: a function declaration must "
- "specify a function return type!";
- const char *errTxt;
- if (errFound)
- errTxt = errinfo;
- else
- errTxt = errno;
- /*
- *在获得字符串的长度上,必须+1,以便在动态分配内存时
- *预留出存储结束符的空间
- */
- int dimension = strlen(errTxt) + 1;
- char *errMsg = new char[dimension];
- strncpy(errMsg,errTxt,dimension);
- //P120 习题4.28
- int main()
- {
- vector<int> ivec;
- int value;
- while (cin >> value)
- {
- ivec.push_back(value);
- }
- int *arr = new int[ivec.size()];
- for (size_t index = 0; index != ivec.size(); ++index)
- {
- arr[index] = ivec[index];
- cout << arr[index] << ' ';
- }
- <span style="white-space:pre"> </span>delete []arr;
- cout << endl;
- }
- //4.29测试下面两段程序的执行时间
- const char *pc = "very long literal string";
- const size_t len = strlen(pc);
- for (size_t ix = 0; ix != 1000000; ++ix)
- {
- char *pc2 = new char[len + 1];
- strcpy(pc2,pc);
- if (strcmp(pc2,pc))
- ;
- delete []pc2;
- }
- //execution time : 0.121 s
- const string obj("very long literal string");
- for (size_t sz = 0; sz != 1000000; ++sz)
- {
- string str = obj;
- if (str != obj)
- ;
- }
- //execution time : 0.071 s
可以看出使用string类型的程序执行速度要比用C风格字符串快很多!!!
- //习题4.30
- //(1)
- int main()
- {
- const char *str1 = "hello";
- const char *str2 = "world";
- const size_t sz = strlen(str1) + strlen(str2) + 2;
- char *strLarg = new char[sz];
- strncpy(strLarg,str1,strlen(str1) + 1);
- strncat(strLarg," ",2);
- strncat(strLarg,str2,sizeof(str2) + 1);
- cout << strLarg << endl;
- delete []strLarg;
- //execution time : 0.002 s
- }
- //(2)
- int main()
- {
- string str1("hello");
- string str2("world");
- string strLarg = str1 + " " + str2;
- cout << strLarg << endl;
- //execution time : 0.002 s
- }