Ponieważ C jest językiem strukturalnym, ma pewne stałe zasady programowania. Jednym z nich jest zmiana rozmiaru tablicy. Tablica to zbiór elementów przechowywanych w sąsiadujących lokalizacjach pamięci.

Jak widać długość (rozmiar) powyższej tablicy wynosi 9. A co jeśli istnieje potrzeba zmiany tej długości (rozmiaru)? Na przykład,
- Jeżeli zaistnieje sytuacja, że w tej tablicy wystarczy wpisać tylko 5 elementów. W tym przypadku pozostałe 4 indeksy po prostu marnują pamięć w tej tablicy. Istnieje zatem wymóg zmniejszenia długości (rozmiaru) tablicy z 9 do 5.
- Weźmy inną sytuację. W tym przypadku istnieje tablica 9 elementów z wypełnionymi wszystkimi 9 indeksami. Istnieje jednak potrzeba wprowadzenia w tej tablicy jeszcze 3 elementów. W tym przypadku wymagane są 3 indeksy więcej. Zatem długość (rozmiar) tablicy należy zmienić z 9 na 12.
Procedura ta nazywana jest Dynamiczna alokacja pamięci w C .
Dlatego C Dynamiczna alokacja pamięci można zdefiniować jako procedurę, w której rozmiar struktury danych (takiej jak tablica) zmienia się w czasie wykonywania.
C zapewnia pewne funkcje umożliwiające realizację tych zadań. Istnieją 4 funkcje biblioteczne udostępniane przez C, zdefiniowane poniżej nagłówkowy, aby ułatwić dynamiczną alokację pamięci w programowaniu C. Oni są:
- malloc()
- kaloc()
- bezpłatny()
- realloc()
Przyjrzyjmy się każdemu z nich bardziej szczegółowo.
Metoda C malloc().
The malloc Lub alokacja pamięci Metoda w języku C służy do dynamicznego przydzielania pojedynczego dużego bloku pamięci o określonym rozmiarze. Zwraca wskaźnik typu void, który można rzucić na wskaźnik w dowolnej formie. Nie inicjuje pamięci w czasie wykonywania, więc początkowo zainicjował każdy blok z domyślną wartością śmieci.
Składnia malloc() w C
ptr = (cast-type*) malloc(byte-size) For Example:>
ptr = (int*) malloc(100 * sizeof(int));
Ponieważ rozmiar int wynosi 4 bajty, ta instrukcja przydzieli 400 bajtów pamięci. Natomiast wskaźnik ptr przechowuje adres pierwszego bajtu przydzielonej pamięci.

Jeśli miejsce jest niewystarczające, alokacja nie powiedzie się i zwróci wskaźnik NULL.
Przykład malloc() w C
C
lista tablic posortowana
#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int>* ptr;> >int> n, i;> >// Get the number of elements for the array> >printf>(>'Enter number of elements:'>);> >scanf>(>'%d'>,&n);> >printf>(>'Entered number of elements: %d
'>, n);> >// Dynamically allocate memory using malloc()> >ptr = (>int>*)>malloc>(n *>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by malloc or not> >if> (ptr == NULL) {> >printf>(>'Memory not allocated.
'>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using malloc.
'>);> >// Get the elements of the array> >for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } } return 0; }> |
>
>Wyjście
Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,>
Metoda C calloc().
- kaloc Lub przydział ciągły metoda w C służy do dynamicznego przydzielania określonej liczby bloków pamięci określonego typu. jest bardzo podobna do malloc(), ale ma dwa różne punkty, a są to:
- Inicjuje każdy blok z domyślną wartością „0”.
- Ma dwa parametry lub argumenty w porównaniu do malloc().
Składnia calloc() w C
ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element.>
Na przykład:
ptr = (float*) calloc(25, sizeof(float));
Ta instrukcja przydziela ciągłą przestrzeń w pamięci dla 25 elementów, każdy o rozmiarze float.

Jeśli miejsce jest niewystarczające, alokacja nie powiedzie się i zwróci wskaźnik NULL.
Przykład calloc() w C
C
aktualizacja z dołączenia do sql
#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int>* ptr;> >int> n, i;> >// Get the number of elements for the array> >n = 5;> >printf>(>'Enter number of elements: %d
'>, n);> >// Dynamically allocate memory using calloc()> >ptr = (>int>*)>calloc>(n,>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by calloc or not> >if> (ptr == NULL) {> >printf>(>'Memory not allocated.
'>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using calloc.
'>);> >// Get the elements of the array> >for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } } return 0; }> |
>
>Wyjście
Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,>
Metoda C free().
bezpłatny metoda w C jest używana dynamicznie zwolnić pamięć. Pamięć przydzielona za pomocą funkcji malloc() i calloc() nie jest sama zwalniana. Dlatego zawsze, gdy ma miejsce dynamiczna alokacja pamięci, używana jest metoda free(). Pomaga zmniejszyć marnowanie pamięci poprzez jej zwolnienie.
Składnia free() w C
free(ptr);>

Przykład free() w C
C
ładowanie javascript
#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int> *ptr, *ptr1;> >int> n, i;> >// Get the number of elements for the array> >n = 5;> >printf>(>'Enter number of elements: %d
'>, n);> >// Dynamically allocate memory using malloc()> >ptr = (>int>*)>malloc>(n *>sizeof>(>int>));> >// Dynamically allocate memory using calloc()> >ptr1 = (>int>*)>calloc>(n,>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by malloc or not> >if> (ptr == NULL || ptr1 == NULL) {> >printf>(>'Memory not allocated.
'>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using malloc.
'>);> >// Free the memory> >free>(ptr);> >printf>(>'Malloc Memory successfully freed.
'>);> >// Memory has been successfully allocated> >printf>(>'
Memory successfully allocated using calloc.
'>);> >// Free the memory> >free>(ptr1);> >printf>(>'Calloc Memory successfully freed.
'>);> >}> >return> 0;> }> |
>
>Wyjście
Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed.>
Metoda realloc() w języku C
realok Lub ponowna alokacja Metoda w C służy do dynamicznej zmiany alokacji pamięci wcześniej przydzielonej. Innymi słowy, jeśli pamięć wcześniej przydzielona za pomocą malloc lub calloc jest niewystarczająca, można zastosować realloc dynamicznie przydzielać pamięć . ponowna alokacja pamięci utrzymuje już obecną wartość, a nowe bloki będą inicjowane z domyślną wartością śmieci.
Składnia realloc() w C
ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.>

Jeśli miejsce jest niewystarczające, alokacja nie powiedzie się i zwróci wskaźnik NULL.
Przykład realloc() w C
C
#include> #include> int> main()> {> >// This pointer will hold the> >// base address of the block created> >int>* ptr;> >int> n, i;> >// Get the number of elements for the array> >n = 5;> >printf>(>'Enter number of elements: %d
'>, n);> >// Dynamically allocate memory using calloc()> >ptr = (>int>*)>calloc>(n,>sizeof>(>int>));> >// Check if the memory has been successfully> >// allocated by malloc or not> >if> (ptr == NULL) {> >printf>(>'Memory not allocated.
'>);> >exit>(0);> >}> >else> {> >// Memory has been successfully allocated> >printf>(>'Memory successfully allocated using calloc.
'>);> >// Get the elements of the array> >for> (i = 0; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } // Get the new size for the array n = 10; printf('
Enter the new size of the array: %d
', n); // Dynamically re-allocate memory using realloc() ptr = (int*)realloc(ptr, n * sizeof(int)); // Memory has been successfully allocated printf('Memory successfully re-allocated using realloc.
'); // Get the new elements of the array for (i = 5; i ptr[i] = i + 1; } // Print the elements of the array printf('The elements of the array are: '); for (i = 0; i printf('%d, ', ptr[i]); } free(ptr); } return 0; }> |
>
>Wyjście
Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5, Enter the new size of the array: 10 Memory successfully re-allocated using realloc. The elements of the array are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,>
Innym przykładem metody realloc() jest:
C
tablica ciągów programu c
#include> #include> int> main()> {> >int> index = 0, i = 0, n,> >*marks;>// this marks pointer hold the base address> >// of the block created> >int> ans;> >marks = (>int>*)>malloc>(>sizeof>(> >int>));>// dynamically allocate memory using malloc> >// check if the memory is successfully allocated by> >// malloc or not?> >if> (marks == NULL) {> >printf>(>'memory cannot be allocated'>);> >}> >else> {> >// memory has successfully allocated> >printf>(>'Memory has been successfully allocated by '> >'using malloc
'>);> >printf>(>'
marks = %pc
'>,> >marks);>// print the base or beginning> >// address of allocated memory> >do> {> >printf>(>'
Enter Marks
'>);> >scanf>(>'%d'>, &marks[index]);>// Get the marks> >printf>(>'would you like to add more(1/0): '>);> >scanf>(>'%d'>, &ans);> >if> (ans == 1) {> >index++;> >marks = (>int>*)>realloc>(> >marks,> >(index + 1)> >*>sizeof>(> >int>));>// Dynamically reallocate> >// memory by using realloc> >// check if the memory is successfully> >// allocated by realloc or not?> >if> (marks == NULL) {> >printf>(>'memory cannot be allocated'>);> >}> >else> {> >printf>(>'Memory has been successfully '> >'reallocated using realloc:
'>);> >printf>(> >'
base address of marks are:%pc'>,> >marks);>////print the base or> >///beginning address of> >///allocated memory> >}> >}> >}>while> (ans == 1);> >// print the marks of the students> >for> (i = 0; i <= index; i++) {> >printf>(>'marks of students %d are: %d
'>, i,> >marks[i]);> >}> >free>(marks);> >}> >return> 0;> }> |
>
>
Wyjście:
