Ce guide explique les différences entre calloc et malloc à travers des exercices pratiques corrigés. Vous apprendrez à choisir la fonction appropriée en fonction des besoins spécifiques.
malloc void *malloc(size_t size); calloc void *calloc(size_t nitems, size_t size); mallocAllouez un tableau de 5 entiers avec malloc, puis initialisez-le à zéro.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array = (int *)malloc(5 * sizeof(int));
if (array == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Initialisation manuelle
for (int i = 0; i < 5; i++) {
array[i] = 0;
}
// Affichage
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
printf("\n");
free(array);
return 0;
} callocRéalisez la même tâche que dans l’exercice précédent, mais utilisez calloc pour simplifier le code.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array = (int *)calloc(5, sizeof(int));
if (array == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Affichage : Pas besoin d'initialisation explicite
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]); // Tous les éléments sont déjà 0
}
printf("\n");
free(array);
return 0;
} malloc et callocAllouez deux tableaux de taille 5, un avec malloc et l’autre avec calloc. Affichez leurs valeurs initiales.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array_malloc = (int *)malloc(5 * sizeof(int));
int *array_calloc = (int *)calloc(5, sizeof(int));
if (array_malloc == NULL || array_calloc == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
printf("Valeurs avec malloc : ");
for (int i = 0; i < 5; i++) {
printf("%d ", array_malloc[i]); // Valeurs indéterminées
}
printf("\n");
printf("Valeurs avec calloc : ");
for (int i = 0; i < 5; i++) {
printf("%d ", array_calloc[i]); // Toutes les valeurs sont 0
}
printf("\n");
free(array_malloc);
free(array_calloc);
return 0;
} malloc et callocCréez une matrice 3×3 (tableau 2D) avec :
malloc : initialisez les valeurs à zéro manuellement.calloc : laissez calloc initialiser la mémoire.malloc :#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3, cols = 3;
int *matrix = (int *)malloc(rows * cols * sizeof(int));
if (matrix == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Initialisation manuelle
for (int i = 0; i < rows * cols; i++) {
matrix[i] = 0;
}
// Affichage
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i * cols + j]);
}
printf("\n");
}
free(matrix);
return 0;
} calloc :#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3, cols = 3;
int *matrix = (int *)calloc(rows * cols, sizeof(int));
if (matrix == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Pas besoin d'initialisation : la mémoire est déjà zéro
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i * cols + j]);
}
printf("\n");
}
free(matrix);
return 0;
} callocDéclarez une structure pour représenter une personne (nom, âge). Allouez un tableau de 3 personnes avec calloc et initialisez leurs valeurs par défaut.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[50];
int age;
} Person;
int main() {
int n = 3;
Person *people = (Person *)calloc(n, sizeof(Person));
if (people == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Pas besoin d'initialiser explicitement : tous les champs sont déjà zéro
for (int i = 0; i < n; i++) {
printf("Personne %d : Nom = '%s', Âge = %d\n", i + 1, people[i].name, people[i].age);
}
free(people);
return 0;
} Allouez un tableau de taille 5 avec calloc, puis redimensionnez-le pour contenir 10 éléments avec realloc. Affichez les valeurs avant et après la réallocation.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array = (int *)calloc(5, sizeof(int));
if (array == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
printf("Avant réallocation : ");
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
printf("\n");
// Réallocation
array = (int *)realloc(array, 10 * sizeof(int));
if (array == NULL) {
printf("Échec de la réallocation.\n");
return 1;
}
printf("Après réallocation : ");
for (int i = 0; i < 10; i++) {
printf("%d ", array[i]); // Les nouveaux éléments ne sont pas initialisés à 0
}
printf("\n");
free(array);
return 0;
} malloc | calloc |
|---|---|
| Alloue la mémoire mais ne l’initialise pas. | Alloue la mémoire et l’initialise à zéro. |
| Peut être plus rapide pour des allocations simples. | Plus sûr pour éviter les erreurs liées à des données non initialisées. |
| Nécessite une initialisation manuelle si nécessaire. | Prêt à l’emploi avec des valeurs nulles ou zéro. |
calloc vs malloc – Exercices CorrigésCe guide explique les différences entre calloc et malloc à travers des exercices pratiques corrigés. Vous apprendrez à choisir la fonction appropriée en fonction des besoins spécifiques.
malloc void *malloc(size_t size); calloc void *calloc(size_t nitems, size_t size); mallocAllouez un tableau de 5 entiers avec malloc, puis initialisez-le à zéro.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array = (int *)malloc(5 * sizeof(int));
if (array == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Initialisation manuelle
for (int i = 0; i < 5; i++) {
array[i] = 0;
}
// Affichage
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
printf("\n");
free(array);
return 0;
} callocRéalisez la même tâche que dans l’exercice précédent, mais utilisez calloc pour simplifier le code.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array = (int *)calloc(5, sizeof(int));
if (array == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Affichage : Pas besoin d'initialisation explicite
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]); // Tous les éléments sont déjà 0
}
printf("\n");
free(array);
return 0;
} malloc et callocAllouez deux tableaux de taille 5, un avec malloc et l’autre avec calloc. Affichez leurs valeurs initiales.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array_malloc = (int *)malloc(5 * sizeof(int));
int *array_calloc = (int *)calloc(5, sizeof(int));
if (array_malloc == NULL || array_calloc == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
printf("Valeurs avec malloc : ");
for (int i = 0; i < 5; i++) {
printf("%d ", array_malloc[i]); // Valeurs indéterminées
}
printf("\n");
printf("Valeurs avec calloc : ");
for (int i = 0; i < 5; i++) {
printf("%d ", array_calloc[i]); // Toutes les valeurs sont 0
}
printf("\n");
free(array_malloc);
free(array_calloc);
return 0;
} malloc et callocCréez une matrice 3×3 (tableau 2D) avec :
malloc : initialisez les valeurs à zéro manuellement.calloc : laissez calloc initialiser la mémoire.malloc :#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3, cols = 3;
int *matrix = (int *)malloc(rows * cols * sizeof(int));
if (matrix == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Initialisation manuelle
for (int i = 0; i < rows * cols; i++) {
matrix[i] = 0;
}
// Affichage
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i * cols + j]);
}
printf("\n");
}
free(matrix);
return 0;
} calloc :#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3, cols = 3;
int *matrix = (int *)calloc(rows * cols, sizeof(int));
if (matrix == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Pas besoin d'initialisation : la mémoire est déjà zéro
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i * cols + j]);
}
printf("\n");
}
free(matrix);
return 0;
} callocDéclarez une structure pour représenter une personne (nom, âge). Allouez un tableau de 3 personnes avec calloc et initialisez leurs valeurs par défaut.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[50];
int age;
} Person;
int main() {
int n = 3;
Person *people = (Person *)calloc(n, sizeof(Person));
if (people == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
// Pas besoin d'initialiser explicitement : tous les champs sont déjà zéro
for (int i = 0; i < n; i++) {
printf("Personne %d : Nom = '%s', Âge = %d\n", i + 1, people[i].name, people[i].age);
}
free(people);
return 0;
} Allouez un tableau de taille 5 avec calloc, puis redimensionnez-le pour contenir 10 éléments avec realloc. Affichez les valeurs avant et après la réallocation.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array = (int *)calloc(5, sizeof(int));
if (array == NULL) {
printf("Échec de l'allocation.\n");
return 1;
}
printf("Avant réallocation : ");
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
printf("\n");
// Réallocation
array = (int *)realloc(array, 10 * sizeof(int));
if (array == NULL) {
printf("Échec de la réallocation.\n");
return 1;
}
printf("Après réallocation : ");
for (int i = 0; i < 10; i++) {
printf("%d ", array[i]); // Les nouveaux éléments ne sont pas initialisés à 0
}
printf("\n");
free(array);
return 0;
} malloc | calloc |
|---|---|
| Alloue la mémoire mais ne l’initialise pas. | Alloue la mémoire et l’initialise à zéro. |
| Peut être plus rapide pour des allocations simples. | Plus sûr pour éviter les erreurs liées à des données non initialisées. |
| Nécessite une initialisation manuelle si nécessaire. | Prêt à l’emploi avec des valeurs nulles ou zéro. |
Télécharger des modèles et exemples Word de lettres de motivation pour mutation interne ⬇️ Au…
Télécharger des modèles et exemples de lettres de motivation pour promotion interne ⬇️ Rédiger une…
Dans beaucoup d’organisations, la production semble avancer sans difficulté. Les ordres circulent, les équipes exécutent,…
À mesure que les systèmes industriels gagnent en complexité, une évidence s’impose avec une clarté…
Le simulateur Kanban flux tiré ⬇️ en ligne permet de traduire les paramètres clés d’un…
La demande dans le secteur de la chaussure ne se résume jamais à un simple…
This website uses cookies.