new 和 malloc() 的區別
在這篇文章中,我們將瞭解“new”和“malloc”之間的區別。
new
它存在於 C++、Java 和 C# 中。
它是一個運算子,可用於呼叫物件的建構函式。
它可以被過載。
如果失敗,則會丟擲異常。
它不需要“sizeof”運算子。
它不會重新分配記憶體。
它可以在為物件分配記憶體時初始化物件。
由“new”運算子分配的記憶體可以使用“delete”運算子釋放。
它減少了應用程式的執行時間。
示例
#include<iostream>
using namespace std;
int main(){
int *val = new int(10);
cout << *val;
getchar();
return 0;
}malloc
這存在於 C 語言中。
它是一個函式,不能被過載。
當“malloc”失敗時,它返回 NULL。
它需要“sizeof”運算子來知道要分配多少記憶體。
它不能呼叫建構函式。
無法使用此函式初始化記憶體。
使用 malloc 分配的記憶體可以使用 free 函式釋放。
使用 malloc 方法分配的記憶體可以使用 realloc 方法重新分配。
它需要更多時間來執行應用程式。
以下是 C 語言中 malloc 的示例:
示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
char *str;
/* Initial memory allocation */
str = (char *) malloc(5);
strcpy(str, "amit");
printf("String = %s, Address = %u
", str, str);
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP