Da C eine strukturierte Sprache ist, gibt es einige feste Regeln für die Programmierung. Eine davon umfasst das Ändern der Größe eines Arrays. Ein Array ist eine Sammlung von Elementen, die an zusammenhängenden Speicherorten gespeichert sind.
Wie Sie sehen können, beträgt die Länge (Größe) des obigen Arrays 9. Was aber, wenn eine Änderung dieser Länge (Größe) erforderlich ist? Zum Beispiel,
- Wenn es eine Situation gibt, in der nur 5 Elemente in dieses Array eingegeben werden müssen. In diesem Fall verschwenden die verbleibenden 4 Indizes lediglich Speicher in diesem Array. Daher besteht die Anforderung, die Länge (Größe) des Arrays von 9 auf 5 zu verringern.
- Nehmen Sie eine andere Situation. Darin gibt es ein Array aus 9 Elementen, bei dem alle 9 Indizes gefüllt sind. Es müssen jedoch noch drei weitere Elemente in dieses Array eingegeben werden. In diesem Fall sind 3 Indizes mehr erforderlich. Daher muss die Länge (Größe) des Arrays von 9 auf 12 geändert werden.
Dieses Verfahren wird als bezeichnet Dynamische Speicherzuweisung in C .
Deshalb, C Dynamische Speicherzuweisung kann als eine Prozedur definiert werden, bei der die Größe einer Datenstruktur (wie Array) während der Laufzeit geändert wird.
C bietet einige Funktionen, um diese Aufgaben zu erfüllen. Es gibt 4 von C bereitgestellte Bibliotheksfunktionen, die unten definiert sind Header-Datei zur Erleichterung der dynamischen Speicherzuweisung bei der C-Programmierung. Sie sind:
- malloc()
- calloc()
- frei()
- realloc()
Schauen wir uns jeden einzelnen davon genauer an.
C malloc()-Methode
Der malloc oder Speicherzuweisung Die Methode in C wird verwendet, um einen einzelnen großen Speicherblock mit der angegebenen Größe dynamisch zuzuweisen. Es gibt einen Zeiger vom Typ void zurück, der in einen Zeiger beliebiger Form umgewandelt werden kann. Der Speicher wird zur Ausführungszeit nicht initialisiert, sodass jeder Block zunächst mit dem Standard-Müllwert initialisiert wird.
Syntax von malloc() in C
ptr = (cast-type*) malloc(byte-size) For Example:>
ptr = (int*) malloc(100 * sizeof(int));
Da die Größe von int 4 Byte beträgt, reserviert diese Anweisung 400 Byte Speicher. Und der Zeiger ptr enthält die Adresse des ersten Bytes im zugewiesenen Speicher.
Wenn der Speicherplatz nicht ausreicht, schlägt die Zuweisung fehl und gibt einen NULL-Zeiger zurück.
Beispiel für 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; }> |
>
>Ausgabe
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 oder zusammenhängende Zuordnung Die Methode in C wird verwendet, um die angegebene Anzahl von Speicherblöcken des angegebenen Typs dynamisch zuzuweisen. Es ist malloc() sehr ähnlich, hat aber zwei verschiedene Punkte und diese sind:
- Es initialisiert jeden Block mit einem Standardwert „0“.
- Es hat zwei Parameter oder Argumente im Vergleich zu malloc().
Syntax von 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.>
Zum Beispiel:
csma und csma cd
ptr = (float*) calloc(25, sizeof(float));
Diese Anweisung weist zusammenhängenden Speicherplatz im Speicher für 25 Elemente mit der Größe des Floats zu.
Wenn der Speicherplatz nicht ausreicht, schlägt die Zuweisung fehl und gibt einen NULL-Zeiger zurück.
Beispiel für 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; }> |
>
>Ausgabe
Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,>
C free()-Methode
frei Methode in C wird dynamisch verwendet freigeben die Erinnerung. Der mit den Funktionen malloc() und calloc() zugewiesene Speicher wird nicht automatisch freigegeben. Daher wird die Methode free() immer dann verwendet, wenn die dynamische Speicherzuweisung stattfindet. Es hilft, die Verschwendung von Speicher zu reduzieren, indem es ihn freigibt.
Syntax von free() in C
free(ptr);>
Beispiel für 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;> }> |
>
>Ausgabe
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 oder Neuzuweisung Die Methode in C wird verwendet, um die Speicherzuweisung eines zuvor zugewiesenen Speichers dynamisch zu ändern. Mit anderen Worten: Wenn der zuvor mit malloc oder calloc zugewiesene Speicher nicht ausreicht, kann realloc verwendet werden Speicher dynamisch neu zuweisen . Durch die Neuzuweisung von Speicher bleibt der bereits vorhandene Wert erhalten und neue Blöcke werden mit dem Standard-Müllwert initialisiert.
Syntax von realloc() in C
ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.>
Wenn der Speicherplatz nicht ausreicht, schlägt die Zuweisung fehl und gibt einen NULL-Zeiger zurück.
Beispiel für 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; }> |
>
>Ausgabe
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,>
Ein weiteres Beispiel für die realloc()-Methode ist:
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;> }> |
>
>
Ausgabe: