Dynamic Memory Allocation for Strings in C
Dynamic memory allocation is often used for handling strings of variable lengths. Functions like malloc, realloc, and free can be used to allocate and manipulate memory for strings.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char* message = (char*)malloc(20 * sizeof(char));
strcpy(message, "Hello, ");
message = (char*)realloc(message, 30 * sizeof(char));
strcat(message, "world!");
printf("%s\n", message);
free(message);
return 0;
}
No comments:
Post a Comment