每一篇博客我都会修改很多次,同学们可以放心浏览.
现在是2022 /5/4 长春市大学生因疫情返乡,我也不例外,所以时间比较少.很难抽出时间整理博客,疫情何时能结束呢?
我尽量举最简单的例子来简化这些语法 C/C++动态申请内存空间写法:#includeC/C++动态申请内存空间并进行初始化写法:#include using namespace std; int main() { int* pC_Num = (int*)malloc(sizeof(int)); free(pC_Num); pC_Num = nullptr; int* pCpp_Num = new int; delete pCpp_Num; pCpp_Num = nullptr; int* pC_Array = (int*)malloc(sizeof(int) * 4); free(pC_Array); pC_Array = nullptr; int* pCpp_Array = new int[4]; delete[] pCpp_Array; pCpp_Array = nullptr; return 0; }
#includeC/C++内存池(比较重要):#include using namespace std; int main() { int* pAlloc = (int*)calloc(sizeof(int), 3); if (pAlloc == nullptr) { return 0; } //assert(pAlloc); cout << pAlloc[0] << pAlloc[1] << pAlloc[2] << endl; free(pAlloc); int* pArray = new int[3]{ 1,2,3 }; cout << pArray[0] << pArray[1] << pArray[2] << endl; delete[] pArray; pArray = nullptr; return 0; }
#include#include #include #include using namespace std; int main() { char* Memory = new char[1024]; assert(Memory); int* pInt = new(Memory + 0) int[3]{1,2,3}; assert(Memory); char* pChar = new(Memory + 12) char[20]; assert(pChar); strcpy(pChar, "我很帅,你也不错"); cout << pInt[0] << pInt[1] << pInt[2] << endl; cout << ((int*)Memory)[0] << ((int*)Memory)[1] << ((int*)Memory)[2] << endl; cout << pChar << endl; cout << Memory + 12 << endl; delete[] Memory; Memory = nullptr; return 0; }



