intmain(){ int table[3][4] = {1,2,3,4,2,3,4,5,3,4,5,6}; for(int i = 0;i < 3;++i){ for(int j = 0;j < 4;++j) cout << table[i][j] << " "; cout << endl; } rowsum(table,3); for(int i = 0;i < 3;++i) cout << "sum of row" << i << " is " << table[i][0] << endl; return0; } /*运行结果*/ 1234 2345 3456 sum of row0 is 11 sum of row1 is 16 sum of row2 is 21
6.2 动态内存分配
6.2.1 建立,删除堆对象new,delete
1 2 3 4 5
new 数据类型(初始化参数列表);//申请成功,返回首地址 int *point; point = newint(2);//*point = 2; point = newint();// *point = 0; point = newint;//不初始化
声明对象内存空间时
若定义默认构造函数, new T 和 new T() 相同
未定义,对该函数的基本数据类型和指针类型数据成员都会被以0赋值
6.2.2 创建、删除数组类型对象
1 2 3 4 5 6
new 类型[数组长度]; delete[] 数组名//加方括号区分普通类型
/*多维数组的申请*/ float* p[25][10];//指针数组 p = newfloat[10][25][10];
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*动态数组类*/ classArrayOfPoints{ public: ArrayOfPoints(int size):size(size){ points = new Point[size]; } ~ArrayOfPoints(){delete[] Points;} Point &element(int index){ assert(index >= 0 && index < size); //在编译模式下起作用,表达式true,继续执行;false,程序终止 return Points[index]; } private: Point *points; int size; }