什么是C中的malloc()? (What is malloc() in C?)
malloc() is a library function that allows C to allocate memory dynamically from the heap. The heap is an area of memory where something is stored.
malloc()是一個庫函數,它允許C從堆動態分配內存。 堆是存儲內容的內存區域。
malloc() is part of stdlib.h and to be able to use it you need to use #include <stdlib.h>
.
malloc()是stdlib.h的一部分,要使用它,您需要使用#include <stdlib.h>
。
如何使用Malloc (How to Use Malloc)
malloc() allocates memory of a requested size and returns a pointer to the beginning of the allocated block. To hold this returned pointer, we must create a variable. The pointer should be of same type used in the malloc statement.Here we’ll make a pointer to a soon-to-be array of ints
malloc()分配請求大小的內存,并返回指向已分配塊開頭的指針。 要保留此返回的指針,我們必須創建一個變量。 該指針應與malloc語句中使用的類型相同。在這里,我們將創建一個指向即將成為整數的數組的指針。
int* arrayPtr;
Unlike other languages, C does not know the data type it is allocating memory for; it needs to be told. Luckily, C has a function called sizeof()
that we can use.
與其他語言不同,C不知道它為其分配內存的數據類型。 它需要被告知。 幸運的是,C有一個我們可以使用的名為sizeof()
的函數。
arrayPtr = (int *)malloc(10 * sizeof(int));
This statement used malloc to set aside memory for an array of 10 integers. As sizes can change between computers, it’s important to use the sizeof() function to calculate the size on the current computer.
該語句使用malloc為10個整數的數組留出內存。 由于大小可以在計算機之間改變,因此使用sizeof()函數計算當前計算機上的大小非常重要。
Any memory allocated during the program’s execution will need to be freed before the program closes. To free
memory, we can use the free() function
在程序關閉之前,必須先釋放程序執行期間分配的所有內存。 要free
內存,我們可以使用free()函數
free( arrayPtr );
This statement will deallocate the memory previously allocated. C does not come with a garbage collector
like some other languages, such as Java. As a result, memory not properly freed will continue to be allocated after the program is closed.
該語句將取消分配先前分配的內存。 C沒有像Java之類的其他語言那樣帶有garbage collector
。 因此,關閉程序后,將繼續分配未正確釋放的內存。
在繼續之前... (Before you go on…)
回顧 (A Review)
- Malloc is used for dynamic memory allocation and is useful when you don’t know the amount of memory needed during compile time. Malloc用于動態內存分配,當您在編譯時不知道所需的內存量時很有用。
- Allocating memory allows objects to exist beyond the scope of the current block. 分配內存允許對象存在于當前塊的范圍之外。
- C passes by value instead of reference. Using malloc to assign memory, and then pass the pointer to another function, is more efficient than having the function recreate the structure. C通過值而不是引用傳遞。 使用malloc分配內存,然后將指針傳遞給另一個函數,比讓函數重新創建結構更有效。
有關C編程的更多信息: (More info on C Programming:)
The beginner's handbook for C programming
C程序設計初學者手冊
If...else statement in C explained
如果...在C中的其他語句解釋了
Ternary operator in C explained
C中的三元運算符說明
翻譯自: https://www.freecodecamp.org/news/malloc-in-c-dynamic-memory-allocation-in-c-explained/