Com que C és un llenguatge estructurat, té unes regles fixes per a la programació. Un d'ells inclou canviar la mida d'una matriu. Una matriu és una col·lecció d'elements emmagatzemats en ubicacions de memòria contigües.

Com es pot veure, la longitud (mida) de la matriu anterior és 9. Però, què passa si hi ha un requisit per canviar aquesta longitud (mida)? Per exemple,
- Si hi ha una situació en què només cal introduir 5 elements en aquesta matriu. En aquest cas, els 4 índexs restants només estan malgastant memòria en aquesta matriu. Per tant, hi ha un requisit per reduir la longitud (mida) de la matriu de 9 a 5.
- Pren una altra situació. En això, hi ha una matriu de 9 elements amb els 9 índexs omplerts. Però cal introduir 3 elements més en aquesta matriu. En aquest cas, calen 3 índexs més. Per tant, la longitud (mida) de la matriu s'ha de canviar de 9 a 12.
Aquest procediment s'anomena Assignació de memòria dinàmica en C .
Per tant, C Assignació de memòria dinàmica es pot definir com un procediment en què la mida d'una estructura de dades (com ara Array) es modifica durant el temps d'execució.
C proporciona algunes funcions per aconseguir aquestes tasques. Hi ha 4 funcions de biblioteca proporcionades per C definides a sota fitxer de capçalera per facilitar l'assignació de memòria dinàmica en programació C. Ells són:
- malloc()
- calloc()
- gratuït ()
- realloc()
Vegem cada un d'ells amb més detall.
Mètode C malloc().
El malloc o assignació de memòria El mètode C s'utilitza per assignar dinàmicament un únic bloc gran de memòria amb la mida especificada. Retorna un punter de tipus void que es pot convertir en un punter de qualsevol forma. No inicialitza la memòria en el moment de l'execució, de manera que inicialment ha inicialitzat cada bloc amb el valor d'escombraries predeterminat.
Sintaxi de malloc() en C
ptr = (cast-type*) malloc(byte-size) For Example:>
ptr = (int*) malloc(100 * sizeof(int));
Com que la mida de int és de 4 bytes, aquesta declaració assignarà 400 bytes de memòria. I, el punter ptr conté l'adreça del primer byte a la memòria assignada.

Si l'espai és insuficient, l'assignació falla i retorna un punter NULL.
Exemple de malloc() en 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; }> |
>
numera l'alfabet
>Sortida
Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,>
Mètode C calloc().
- calloc o assignació contigua El mètode C s'utilitza per assignar dinàmicament el nombre especificat de blocs de memòria del tipus especificat. és molt semblant a malloc() però té dos punts diferents i aquests són:
- Inicialitza cada bloc amb un valor per defecte '0'.
- Té dos paràmetres o arguments en comparació amb malloc().
Sintaxi de calloc() en C
ptr = (cast-type*)calloc(n, element-size); here, n is the no. of elements and element-size is the size of each element.>
Per exemple:
ptr = (float*) calloc(25, sizeof (float));
Aquesta declaració assigna espai contigu a la memòria per a 25 elements cadascun amb la mida del flotant.

Si l'espai és insuficient, l'assignació falla i retorna un punter NULL.
Exemple de calloc() a 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; }> |
>
>Sortida
Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,>
Mètode C free().
lliure El mètode en C s'utilitza per dinàmicament de-allocate la memòria. La memòria assignada mitjançant les funcions malloc() i calloc() no es desassigna per si sola. Per tant, s'utilitza el mètode free() sempre que es produeix l'assignació de memòria dinàmica. Ajuda a reduir el malbaratament de memòria alliberant-la.
clau del candidat
Sintaxi de free() en C
free(ptr);>

Exemple de free() a 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;> }> |
>
>Sortida
Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed.>
Mètode C realloc().
realloc o reassignació El mètode C s'utilitza per canviar dinàmicament l'assignació de memòria d'una memòria assignada prèviament. En altres paraules, si la memòria prèviament assignada amb l'ajuda de malloc o calloc és insuficient, es pot utilitzar realloc per reassignar dinàmicament la memòria . la reassignació de memòria manté el valor ja present i els nous blocs s'inicializaran amb el valor d'escombraries predeterminat.
Sintaxi de realloc() en C
ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.>

Si l'espai és insuficient, l'assignació falla i retorna un punter NULL.
Exemple de realloc() a 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; }> |
>
>Sortida
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,>
Un altre exemple per al mètode realloc() és:
C
rakhi sawant
#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;> }> |
>
>
Sortida:
