int size = 0;
cin >> size;
char* arr = new char[size];
arr[0]='c';
int i = reinterpret_cast<int>(arr);//137000
char c = *reinterpret_cast<char*>(i);//'c'
cout<<"sizeof(arr) is "<<sizeof(arr)<<endl;//4
cout<<"arr size is "<< *reinterpret_cast<int*>(reinterpret_cast<int>(arr) - sizeof(int)*4)<<endl;//size
delete[] arr;
由上面的程序可知在运行时程序在堆上开辟一段空间给arr,并在arr的首地址前面记录下arr数组的大小,这样delete[]就可以知道要释放掉多大的数组。这个工作并不是编译器完成的。
本文探讨了C++中使用new与delete[]操作符管理动态数组的过程。具体介绍了如何在堆上为字符数组分配内存,并通过reinterpret_cast来读取记录在数组首地址前的大小信息,以便正确释放内存。
202

被折叠的 条评论
为什么被折叠?



