Eftersom C är ett strukturerat språk har det några fasta regler för programmering. En av dem inkluderar att ändra storleken på en array. En array är en samling objekt lagrade på sammanhängande minnesplatser.

Som kan ses är längden (storleken) på arrayen ovan 9. Men vad händer om det finns ett krav på att ändra denna längd (storlek)? Till exempel,
- Om det finns en situation där endast 5 element behövs för att matas in i denna array. I det här fallet slösar de återstående 4 indexen bara bort minne i denna array. Så det finns ett krav på att minska längden (storleken) på arrayen från 9 till 5.
- Ta en annan situation. I detta finns en uppsättning av 9 element med alla 9 index fyllda. Men det finns ett behov av att ange ytterligare 3 element i denna array. I det här fallet krävs ytterligare 3 index. Så längden (storleken) på arrayen måste ändras från 9 till 12.
Denna procedur kallas Dynamisk minnesallokering i C .
Därför C Dynamisk minnesallokering kan definieras som en procedur där storleken på en datastruktur (som Array) ändras under körningen.
C tillhandahåller några funktioner för att uppnå dessa uppgifter. Det finns 4 biblioteksfunktioner som tillhandahålls av C definierade under header-fil för att underlätta dynamisk minnesallokering i C-programmering. Dom är:
- malloc()
- calloc()
- fri()
- realloc()
Låt oss titta på var och en av dem mer i detalj.
rensa cache npm
C malloc() metod
De malloc eller minnesallokering metod i C används för att dynamiskt allokera ett enda stort minnesblock med den angivna storleken. Den returnerar en pekare av typen void som kan gjutas till en pekare av vilken form som helst. Det initierar inte minnet vid körning så att det initialt har initierat varje block med standardvärdet för skräp.
Syntax för malloc() i C
ptr = (cast-type*) malloc(byte-size) For Example:>
ptr = (int*) malloc(100 * sizeof(int));
Eftersom storleken på int är 4 byte, kommer denna sats att allokera 400 byte minne. Och pekaren ptr håller adressen för den första byten i det allokerade minnet.

Om utrymmet är otillräckligt misslyckas allokeringen och returnerar en NULL-pekare.
Exempel på malloc() i 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; }> |
>
>Produktion
Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,>
C calloc() metod
- calloc eller sammanhängande tilldelning metod i C används för att dynamiskt allokera det specificerade antalet minnesblock av den angivna typen. den är väldigt lik malloc() men har två olika punkter och dessa är:
- Den initierar varje block med ett standardvärde '0'.
- Den har två parametrar eller argument i jämförelse med malloc().
Syntax för calloc() i C
ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element.>
Till exempel:
ptr = (float*) calloc(25, sizeof(float));
Detta uttalande tilldelar sammanhängande utrymme i minnet för 25 element vardera med storleken på float.

Om utrymmet är otillräckligt misslyckas allokeringen och returnerar en NULL-pekare.
Exempel på calloc() i 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; }> |
>
>Produktion
Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,>
C free() metod
fri metod i C används för att dynamiskt avfördelning minnet. Minnet som allokeras med funktionerna malloc() och calloc() avallokeras inte på egen hand. Därför används metoden free() närhelst den dynamiska minnesallokeringen äger rum. Det hjälper till att minska slöseri med minne genom att frigöra det.
Syntax för free() i C
free(ptr);>

Exempel på free() i 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;> }> |
>
>Produktion
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() metod
realloc eller omfördelning metod i C används för att dynamiskt ändra minnesallokeringen för ett tidigare tilldelat minne. Med andra ord, om minnet som tidigare allokerats med hjälp av malloc eller calloc är otillräckligt, kan realloc användas för att dynamiskt omallokera minne . omallokering av minne bibehåller det redan nuvarande värdet och nya block kommer att initieras med standardvärdet för skräp.
Syntax för realloc() i C
ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.>

Om utrymmet är otillräckligt misslyckas allokeringen och returnerar en NULL-pekare.
Exempel på realloc() i 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; }> |
>
>Produktion
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,>
Ett annat exempel för metoden realloc() är:
C
tcp och ip-modell
#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;> }> |
>
>
Produktion:
