C++ 动态内存

C++ 动态内存
了解动态内存在 C++ 中是如何工作的是成为一名合格的 C++ 程序员必不可少的。C++ 程序中的内存分为两个部分:

栈:在函数内部声明的所有变量都将占用栈内存。
堆:这是程序中未使用的内存,在程序运行时可用于动态分配内存。
很多时候,您无法提前预知需要多少内存来存储某个定义变量中的特定信息,所需内存的大小需要在运行时才能确定。

在 C++ 中,您可以使用特殊的运算符为给定类型的变量在运行时分配堆内的内存,这会返回所分配的空间地址。这种运算符即 new 运算符。

如果您不再需要动态分配的内存空间,可以使用 delete 运算符,删除之前由 new 运算符分配的内存。

 1 #include <iostream>
 2 
 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 4 using namespace std; 
 5 int main(int argc, char** argv) {
 6     int a[2][3]={{1,2,3},{4,5,6}};
 7     int b[3][2],i,j;
 8     cout <<"array a:"<<endl;
 9     for(i=0;i<=1;i++)
10     {
11         for(j=0;j<=2;j++)
12         {
13             cout <<a[i][j]<<" ";
14             b[j][i]=a[i][j];
15         }
16         cout <<endl;
17     }
18     cout <<"array b:" <<endl;
19     for(i=0;i<=2;i++)
20     {
21         for(j=0;j<=1;j++)
22         cout <<b[i][j]<<" ";
23         cout <<endl;
24     }
25     return 0;
26 }

猜你喜欢

转载自www.cnblogs.com/borter/p/9401279.html