C++面試經常會問到關于malloc/free和new/delete的區別,網上有不同版本的解釋,這里總結下并加上個人理解和使用。
兩者相同點
兩者不同點
注意事項
使用
#include "stdafx.h"#include <stdio.h>#include "stdlib.h"#include <string.h>struct Stu{ char name[32]; int age;};int main(){/**************************** 基本用法 **********************************/ //申請一個int類型 int *p1 = new int; //直接申請賦值 int* p1 = new int(3); int *p2 = (int*)malloc(sizeof(int)); //申請一個char類型 char *p3 = new char; //直接申請賦值 char *p3 = new char('c'); char *p4 = (char*)malloc(sizeof(char)); //申請一個int型一維數組 int *p5 = new int[5]; //直接申請賦值 int *p5 = new int[5]{1,2,3,4,5}; int *p6 = (int*)malloc(sizeof(int)*5); //申請一個char型一維數組 char* p7 = new char[6]; //直接申請賦值 char* p7 = new char[3]{'a', 'v', 'c'}; char* p8 = (char*)malloc(sizeof(char)*6); //申請一個int型二維數組 int(*p9)[2] = new int[2][2]; //直接申請賦值 int(*p9)[2] = new int[2][2]{ 1,2,3,4 }; int(*p10)[2] = (int(*)[2])malloc(sizeof(int)*2*2); //申請一個char型二維數組 char(*p11)[2] = new char[2][2]; char(*p12)[2] = (char(*)[2])malloc(sizeof(char)*2*2);/***************************** 申請二級指針內存 **********************************/ //申請二級指針(new,delete) char** p13 = new char*[2]; p13[0] = "aaaaaaaaaa"; p13[1] = "vvvvvvvvvv"; delete p13; //申請二級指針(malloc, free) char** p14 = (char**)malloc(sizeof(char*)*2); p14[0] = "cccccccc"; p14[1] = "dddddddd"; delete p14;/****************************** 申請結構體內存 *********************************/ //new delete Stu* pStu1 = new Stu; Stu* pStu2 = new Stu{"wpf", 10}; Stu* pStu3 = new Stu[1024]; delete pStu1; delete pStu2; delete[] pStu3; //malloc free Stu* pStu4 = (Stu*)malloc(sizeof(Stu)); memset(pStu4, 0, sizeof(Stu)); free(pStu4); getchar();}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答