logo

Dinamiskā atmiņas piešķiršana C, izmantojot malloc (), calloc (), free () un realloc ()

Tā kā C ir strukturēta valoda, tai ir daži noteikti programmēšanas noteikumi. Viens no tiem ietver masīva lieluma maiņu. Masīvs ir vienumu kolekcija, kas glabājas blakus esošās atmiņas vietās.

masīvi



Kā redzams, augšā esošā masīva garums (izmērs) ir 9. Bet ja ir prasība mainīt šo garumu (izmēru)? Piemēram,

  • Ja ir situācija, kad šajā masīvā ir jāievada tikai 5 elementi. Šajā gadījumā atlikušie 4 indeksi tikai tērē atmiņu šajā masīvā. Tātad ir prasība samazināt masīva garumu (izmēru) no 9 uz 5.
  • Paņemiet citu situāciju. Tajā ir 9 elementu masīvs ar aizpildītiem 9 indeksiem. Bet šajā masīvā ir jāievada vēl 3 elementi. Šajā gadījumā ir nepieciešami vēl 3 indeksi. Tātad masīva garums (izmērs) ir jāmaina no 9 uz 12.

Šo procedūru sauc par Dinamiskā atmiņas piešķiršana C .
Tāpēc C Dinamiskā atmiņas piešķiršana var definēt kā procedūru, kurā izpildlaika laikā tiek mainīts datu struktūras lielums (piemēram, masīvs).
C nodrošina dažas funkcijas šo uzdevumu veikšanai. Ir 4 bibliotēkas funkcijas, ko nodrošina C, kas definēts zemāk galvenes fails, lai atvieglotu dinamisku atmiņas piešķiršanu C programmēšanā. Viņi ir:

  1. malloc ()
  2. calloc()
  3. bezmaksas ()
  4. realloc()

Apskatīsim katru no tiem sīkāk.



C malloc() metode

The malloc vai atmiņas piešķiršana metode C tiek izmantota, lai dinamiski piešķirtu vienu lielu atmiņas bloku ar norādīto izmēru. Tas atgriež tukšuma tipa rādītāju, ko var ievietot jebkuras formas rādītājā. Tas neinicializē atmiņu izpildes laikā, tāpēc katrs bloks sākotnēji ir inicializēts ar noklusējuma atkritumu vērtību.

Malloc() sintakse valodā C

ptr = (cast-type*) malloc(byte-size)   For Example:>

ptr = (int*) malloc(100 * sizeof(int));
Tā kā int lielums ir 4 baiti, šis paziņojums atvēlēs 400 baitus atmiņas. Un rādītājs ptr satur pirmā baita adresi piešķirtajā atmiņā.



Ja vietas nepietiek, piešķiršana neizdodas un atgriež NULL rādītāju.

Malloc() piemērs valodā C

C




saraksts uz java

#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; }>

>

>

Izvade

Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,>

C calloc() metode

  1. calloc vai blakus esošais sadalījums metode C tiek izmantota, lai dinamiski piešķirtu noteiktu skaitu norādītā tipa atmiņas bloku. tas ir ļoti līdzīgs malloc (), bet tam ir divi dažādi punkti, un tie ir:
  2. Tas inicializē katru bloku ar noklusējuma vērtību “0”.
  3. Tam ir divi parametri vai argumenti, salīdzinot ar malloc ().

Calloc() sintakse valodā C

ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element.>

Piemēram:

ptr = (pludiņš*) calloc(25, sizeof(peld));
Šis paziņojums piešķir blakus vietu atmiņā 25 elementiem, katrs ar pludiņa izmēru.

Ja vietas nepietiek, piešķiršana neizdodas un atgriež NULL rādītāju.

Calloc() piemērs valodā 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 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; }>

noķer un izmēģini javu
>

>

Izvade

Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,>

C free() metode

bezmaksas metode C tiek izmantota, lai dinamiski atņemt piešķiršanu atmiņa. Atmiņa, kas piešķirta, izmantojot funkcijas malloc() un calloc(), netiek atdalīta atsevišķi. Līdz ar to free() metode tiek izmantota ikreiz, kad notiek dinamiskā atmiņas piešķiršana. Tas palīdz samazināt atmiņas zudumu, atbrīvojot to.

Free() sintakse valodā C

free(ptr);>

Free() piemērs valodā C

C




#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;> }>

>

>

Izvade

Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed.>

C realloc() metode

realloc vai pārdalīšana metode C tiek izmantota, lai dinamiski mainītu iepriekš piešķirtās atmiņas atmiņas sadalījumu. Citiem vārdiem sakot, ja ar malloc vai calloc palīdzību iepriekš piešķirtā atmiņa ir nepietiekama, realloc var izmantot, lai dinamiski pārdalīt atmiņu . Atmiņas pārdalīšana saglabā jau esošo vērtību, un jaunie bloki tiks inicializēti ar noklusējuma atkritumu vērtību.

Realloc() sintakse valodā C

ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.>

Ja vietas nepietiek, piešķiršana neizdodas un atgriež NULL rādītāju.

Realloc() piemērs 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; }>

>

>

Izvade

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,>

Vēl viens realloc () metodes piemērs ir:

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;> }>

>

>

Izvade:

javascript window.open