You use malloc and calloc to allocate memory dynamically—especially useful when:
char* str = (char*) malloc(size_in_bytes);
char* str = (char*) calloc(num_elements, size_of_each);
💡 calloc also zero-initializes the memory, unlike malloc.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int len = 20;
char* str = (char*)malloc(len * sizeof(char));
if (str == NULL) {
printf("Memory allocation failed!\\n");
return 1;
}
strcpy(str, "Dynamic Hello");
printf("String: %s\\n", str);
free(str); // ⚠️ Always free dynamically allocated memory
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int len = 30;
char* str = (char*)calloc(len, sizeof(char)); // zero-initialized
if (str == NULL) {
printf("Memory allocation failed!\\n");
return 1;
}
strcat(str, "Using calloc");
printf("String: %s\\n", str);
free(str);
return 0;
}