[英]Array creation int *array = new int[sizeof(int)*n]
你能解釋一下這個語句發生了什么,特別是在括號內嗎?
int *array = new int[sizeof(int) * n];
這是一個完整的 C++ 語句, sizeof
運算符的括號()
包含int
類型,而sizeof(type)
以字節為單位給出封閉類型的大小:
int *array = new int[ sizeof(int) * n ];
^^^^^
我相信您的意思是new
表達式的方括號[]
內的表達式,即sizeof(int) * n
。
從語義上講,表達式可能是錯誤的。
如果您使用new
運算符分配 10 個整數,則sizeof(int)
會自動處理。 您只需提供要分配的類型的元素數量。
例如:
int n = 10; // n can be an integer entered by the user
int* a = new int[n]; // allocate an array of 10 integers
在這種情況下,數組元素將被默認初始化,並返回指向數組第一個元素的指針。
而且,當您這樣做時(假設您在 64 位機器上,即sizeof(int)
為 8):
int n = 10;
int s = sizeof(int) * n; // 8 x 10 = 80
int* a = new int[ s ]; // allocate an array of 80 integers
這就是我之前所說的語義錯誤,因為意圖可能是分配 10 個整數,而不是 80 個。
malloc()
需要表達式sizeof(int) * n
,您必須提供要分配的確切字節數,因此您需要提供該類型元素的確切數量。 malloc()
function 不會初始化分配的字節,它也會返回指向第一個元素的指針。
例如:
int n = 10;
int s = sizeof(int) * n;
int* a = (int*) malloc( s );
您必須初始化malloc()
分配的 memory 。 有關這方面的更多信息,請參閱上面的new
和malloc()
鏈接。
除此之外,您正在分配 memory 因此您有責任在完成后釋放它。 因此,理想情況下, new
和new[]
將分別跟隨delete
和delete[]
。 而且, malloc()
之后將是free()
。
有關基於RAII的自動 memory 管理,請參閱智能指針,例如std::unique_pointer和std::shared_ptr以及std::make_unique
和std::make_shared
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.