Dynamic Memory Allocation for Strings in C

 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

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...