logo

Dinaminis atminties paskirstymas C naudojant malloc (), calloc (), free () ir realloc ()

Kadangi C yra struktūrinė kalba, ji turi tam tikras fiksuotas programavimo taisykles. Vienas iš jų apima masyvo dydžio keitimą. Masyvas yra elementų, saugomų gretimose atminties vietose, rinkinys.

masyvai



Kaip matyti, aukščiau esančio masyvo ilgis (dydis) yra 9. O kas, jei yra reikalavimas pakeisti šį ilgį (dydį)? Pavyzdžiui,

  • Jei yra situacija, kai į šį masyvą reikia įvesti tik 5 elementus. Šiuo atveju likę 4 indeksai tiesiog eikvoja atmintį šiame masyve. Taigi yra reikalavimas sumažinti masyvo ilgį (dydį) nuo 9 iki 5.
  • Imkitės kitos situacijos. Čia yra 9 elementų masyvas su užpildytais 9 indeksais. Tačiau į šį masyvą reikia įvesti dar 3 elementus. Šiuo atveju reikia dar 3 indeksų. Taigi masyvo ilgį (dydį) reikia pakeisti nuo 9 iki 12.

Ši procedūra vadinama Dinaminis atminties paskirstymas C .
Todėl C Dinaminis atminties paskirstymas gali būti apibrėžta kaip procedūra, kurios metu duomenų struktūros (pvz., Array) dydis keičiamas vykdymo metu.
C suteikia tam tikras funkcijas šioms užduotims atlikti. Yra 4 bibliotekos funkcijos, kurias teikia C, apibrėžta žemiau antraštės failas, palengvinantis dinaminį atminties paskirstymą programuojant C. Jie yra:

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

Pažvelkime į kiekvieną iš jų išsamiau.



C malloc() metodas

The malloc arba atminties paskirstymas C metodas naudojamas dinamiškai paskirstyti vieną didelį nurodyto dydžio atminties bloką. Jis grąžina tuščiosios rūšies rodyklę, kurią galima įvesti į bet kokios formos žymeklį. Vykdymo metu ji neinicijuoja atminties, todėl iš pradžių kiekvieną bloką inicijuoja numatytąją šiukšlių reikšmę.

Malloc() sintaksė C

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

ptr = (int*) malloc(100 * sizeof(int));
Kadangi int dydis yra 4 baitai, šis teiginys skirs 400 baitų atminties. Ir rodyklė ptr turi pirmojo baito adresą skirtoje atmintyje.



Jei vietos nepakanka, paskirstymas nepavyksta ir grąžinamas NULL žymeklis.

Malloc() pavyzdys 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> >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; }>

>

>

Išvestis

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

C calloc() metodas

  1. calloc arba gretimas paskirstymas C metodas naudojamas dinamiškai paskirstyti nurodytą nurodyto tipo atminties blokų skaičių. jis labai panašus į malloc(), bet turi du skirtingus taškus:
  2. Jis inicijuoja kiekvieną bloką numatytąją reikšmę „0“.
  3. Jis turi du parametrus arba argumentus, palyginti su malloc ().

Calloc() sintaksė C

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

Pavyzdžiui:

skirtumas tarp liūto ir tigro

ptr = (float*) calloc(25, sizeof(float));
Šis teiginys priskiria gretimos vietos atmintyje 25 elementams, kurių kiekvienas turi plūdės dydį.

Jei vietos nepakanka, paskirstymas nepavyksta ir grąžinamas NULL žymeklis.

Calloc() pavyzdys 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; }>

>

>

Išvestis

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

C free() metodas

Laisvas metodas C yra naudojamas dinamiškai panaikinti paskirstymą Atmintis. Atmintis, paskirstyta naudojant funkcijas malloc() ir calloc(), nėra panaikinama atskirai. Taigi, kai vyksta dinaminis atminties paskirstymas, naudojamas free() metodas. Tai padeda sumažinti atminties švaistymą, atlaisvindama ją.

Free() sintaksė C

free(ptr);>

Free() pavyzdys 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;> }>

>

>

json json pavyzdyje
Išvestis

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() metodas

realloc arba perskirstymas C metodas naudojamas dinamiškai pakeisti anksčiau skirtos atminties paskirstymą. Kitaip tariant, jei atminties, kuri anksčiau buvo skirta malloc arba calloc pagalba, nepakanka, realloc galima naudoti dinamiškai perskirstyti atmintį . perskirstant atmintį išlaikoma jau esama reikšmė, o nauji blokai bus inicijuojami naudojant numatytąją šiukšlių reikšmę.

Realloc() sintaksė C

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

Jei vietos nepakanka, paskirstymas nepavyksta ir grąžinamas NULL žymeklis.

Realloc() pavyzdys 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; }>

>

>

Išvestis

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

Kitas realloc () metodo pavyzdys yra:

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

>

>

Išvestis: