Le C étant un langage structuré, il comporte des règles de programmation fixes. L'un d'eux consiste à modifier la taille d'un tableau. Un tableau est une collection d’éléments stockés dans des emplacements mémoire contigus.

Comme on peut le voir, la longueur (taille) du tableau ci-dessus est de 9. Mais que se passe-t-il s'il est nécessaire de modifier cette longueur (taille) ? Par exemple,
- S'il existe une situation où seuls 5 éléments doivent être saisis dans ce tableau. Dans ce cas, les 4 indices restants ne font que gaspiller de la mémoire dans ce tableau. Il est donc nécessaire de réduire la longueur (taille) du tableau de 9 à 5.
- Prenons une autre situation. En cela, il y a un tableau de 9 éléments avec les 9 indices remplis. Mais il est nécessaire de saisir 3 éléments supplémentaires dans ce tableau. Dans ce cas, 3 indices supplémentaires sont nécessaires. La longueur (taille) du tableau doit donc être modifiée de 9 à 12.
Cette procédure est appelée Allocation dynamique de mémoire en C .
Par conséquent, C Allocation de mémoire dynamique peut être défini comme une procédure dans laquelle la taille d'une structure de données (comme un tableau) est modifiée pendant l'exécution.
C fournit quelques fonctions pour accomplir ces tâches. Il existe 4 fonctions de bibliothèque fournies par C définies sous fichier d'en-tête pour faciliter l'allocation dynamique de mémoire dans la programmation C. Ils sont:
- malloc()
- calloc()
- gratuit()
- réaffecter()
Examinons chacun d’eux plus en détail.
Méthode C malloc()
Le malloc ou allocation de mémoire La méthode en C est utilisée pour allouer dynamiquement un seul gros bloc de mémoire avec la taille spécifiée. Il renvoie un pointeur de type void qui peut être transformé en pointeur de n'importe quelle forme. Il n'initialise pas la mémoire au moment de l'exécution, de sorte qu'il initialise initialement chaque bloc avec la valeur de mémoire par défaut.
Syntaxe de malloc() en C
ptr = (cast-type*) malloc(byte-size) For Example:>
ptr = (int*) malloc(100 * sizeof(int));
Puisque la taille de int est de 4 octets, cette instruction allouera 400 octets de mémoire. Et le pointeur ptr contient l’adresse du premier octet dans la mémoire allouée.

Si l'espace est insuffisant, l'allocation échoue et renvoie un pointeur NULL.
Exemple de malloc() en C
C
différence entre le lion et le tigre
#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; }> |
>
>Sortir
Enter number of elements: 5 Memory successfully allocated using malloc. The elements of the array are: 1, 2, 3, 4, 5,>
Méthode C calloc()
- calloc ou allocation contiguë La méthode en C est utilisée pour allouer dynamiquement le nombre spécifié de blocs de mémoire du type spécifié. il est très similaire à malloc() mais comporte deux points différents :
- Il initialise chaque bloc avec une valeur par défaut « 0 ».
- Il a deux paramètres ou arguments par rapport à malloc().
Syntaxe 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.>
Par exemple:
ptr = (float*) calloc(25, sizeof(float));
Cette instruction alloue un espace contigu en mémoire pour 25 éléments chacun avec la taille du float.

Si l'espace est insuffisant, l'allocation échoue et renvoie un pointeur NULL.
Exemple de calloc() en C
C
liste de liens java
#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; }> |
>
>Sortir
Enter number of elements: 5 Memory successfully allocated using calloc. The elements of the array are: 1, 2, 3, 4, 5,>
Méthode C libre()
gratuit La méthode en C est utilisée pour dynamiquement désaffecter la mémoire. La mémoire allouée à l'aide des fonctions malloc() et calloc() n'est pas désallouée d'elle-même. Par conséquent, la méthode free() est utilisée chaque fois que l’allocation dynamique de mémoire a lieu. Cela permet de réduire le gaspillage de mémoire en la libérant.
Syntaxe de free() en C
free(ptr);>

Exemple de free() en C
C
chargement javascript
#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;> }> |
>
>Sortir
Enter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed.>
Méthode C realloc()
réaffectation ou réaffectation La méthode en C est utilisée pour modifier dynamiquement l’allocation de mémoire d’une mémoire précédemment allouée. En d’autres termes, si la mémoire précédemment allouée à l’aide de malloc ou calloc est insuffisante, realloc peut être utilisée pour réallouer dynamiquement la mémoire . la réallocation de mémoire maintient la valeur déjà présente et les nouveaux blocs seront initialisés avec la valeur poubelle par défaut.
Syntaxe de realloc() en C
ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'.>

Si l'espace est insuffisant, l'allocation échoue et renvoie un pointeur NULL.
Exemple de realloc() 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> >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; }> |
>
>Sortir
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 autre exemple de méthode realloc() est :
C
âge rekha
#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;> }> |
>
>
Sortir:
