Omdat C een gestructureerde taal is, heeft het een aantal vaste programmeerregels. Eén daarvan omvat het wijzigen van de grootte van een array. Een array is een verzameling items die zijn opgeslagen op aangrenzende geheugenlocaties.

Zoals u kunt zien, is de lengte (grootte) van de bovenstaande array 9. Maar wat als er een vereiste is om deze lengte (grootte) te wijzigen? Bijvoorbeeld,
- Als er een situatie is waarin slechts 5 elementen in deze array hoeven te worden ingevoerd. In dit geval verspillen de resterende vier indices alleen maar geheugen in deze array. Er is dus een vereiste om de lengte (grootte) van de array te verkleinen van 9 naar 5.
- Neem een andere situatie. Hierin is er een array van 9 elementen met alle 9 indices gevuld. Maar er moeten nog drie elementen in deze array worden ingevoerd. In dit geval zijn er nog 3 indices nodig. De lengte (grootte) van de array moet dus worden gewijzigd van 9 naar 12.
Deze procedure wordt genoemd Dynamische geheugentoewijzing in C .
Daarom C Dynamische geheugentoewijzing kan worden gedefinieerd als een procedure waarbij de grootte van een datastructuur (zoals Array) tijdens de runtime wordt gewijzigd.
C biedt een aantal functies om deze taken uit te voeren. Er zijn 4 bibliotheekfuncties voorzien door C gedefinieerd onder header-bestand om dynamische geheugentoewijzing in C-programmering te vergemakkelijken. Zij zijn:
- malloc()
- calloc()
- vrij()
- realloc()
Laten we ze allemaal in meer detail bekijken.
C malloc()-methode
De malloc of geheugen toewijzing De methode in C wordt gebruikt om dynamisch een enkel groot blok geheugen met de opgegeven grootte toe te wijzen. Het retourneert een aanwijzer van het type void die in een aanwijzer van welke vorm dan ook kan worden gegoten. Het initialiseert het geheugen niet tijdens de uitvoering, zodat het elk blok aanvankelijk met de standaard garbage-waarde heeft geïnitialiseerd.
Syntaxis van malloc() in C
ptr = (cast-type*) malloc(byte-size) For Example:>
ptr = (int*) malloc(100 * groottevan(int));
Omdat de grootte van int 4 bytes is, wijst deze instructie 400 bytes geheugen toe. En de pointer ptr bevat het adres van de eerste byte in het toegewezen geheugen.

Als er onvoldoende ruimte is, mislukt de toewijzing en wordt een NULL-aanwijzer geretourneerd.
Voorbeeld van malloc() in 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; }> |
>
>Uitvoer
Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,>
C calloc()-methode
- calloc of aaneengesloten toewijzing De methode in C wordt gebruikt om het gespecificeerde aantal geheugenblokken van het gespecificeerde type dynamisch toe te wijzen. het lijkt erg op malloc() maar heeft twee verschillende punten en deze zijn:
- Het initialiseert elk blok met de standaardwaarde ‘0’.
- Het heeft twee parameters of argumenten in vergelijking met malloc().
Syntaxis van calloc() in C
ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element.>
Bijvoorbeeld:
ptr = (zwevend*) calloc(25, groottevan(zwevend));
Deze verklaring wijst aaneengesloten ruimte in het geheugen toe voor 25 elementen, elk met de grootte van de float.
kaart Java

Als er onvoldoende ruimte is, mislukt de toewijzing en wordt een NULL-aanwijzer geretourneerd.
Voorbeeld van calloc() in 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; }> |
>
>Uitvoer
Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,>
C free()-methode
vrij methode in C wordt dynamisch gebruikt de-toewijzen de herinnering. Het geheugen dat is toegewezen met behulp van de functies malloc() en calloc() wordt niet op zichzelf ongedaan gemaakt. Daarom wordt de free()-methode gebruikt telkens wanneer de dynamische geheugentoewijzing plaatsvindt. Het helpt geheugenverspilling te verminderen door het vrij te maken.
Syntaxis van free() in C
free(ptr);>

Voorbeeld van free() in 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;> }> |
>
>Uitvoer
array-slicing van Java
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()-methode
realloc of herverdeling methode in C wordt gebruikt om de geheugentoewijzing van een eerder toegewezen geheugen dynamisch te wijzigen. Met andere woorden, als het geheugen dat eerder is toegewezen met behulp van malloc of calloc onvoldoende is, kan realloc worden gebruikt geheugen dynamisch opnieuw toewijzen . Bij het opnieuw toewijzen van geheugen blijft de reeds aanwezige waarde behouden en nieuwe blokken worden geïnitialiseerd met de standaard garbage-waarde.
Syntaxis van realloc() in C
ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.>

Als er onvoldoende ruimte is, mislukt de toewijzing en wordt een NULL-aanwijzer geretourneerd.
Voorbeeld van realloc() in 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; }> |
>
>Uitvoer
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,>
Een ander voorbeeld voor de realloc() methode is:
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;> }> |
>
>
Uitgang:
