Dynamic Memory Allocation for Strings in C

 Dynamic Memory Allocation for Strings in C


Dynamic memory allocation is commonly used when working with strings in C. By allocating memory dynamically, you can handle strings of varying lengths and avoid fixed-size limitations.


#include <stdio.h>

#include <stdlib.h>

#include <string.h>


int main() {

    char* name = (char*)malloc(20 * sizeof(char));


    if (name == NULL) {

        printf("Memory allocation failed.\n");

        return 1;

    }


    printf("Enter your name: ");

    scanf("%19s", name);


    int nameLength = strlen(name);

    printf("Length of the name: %d\n", nameLength);


    printf("Hello, %s!\n", name);


    free(name);


    return 0;

}

In this example, memory is dynamically allocated to store a name of up to 19 characters. The strlen function is used to determine the length of the entered name, and free is called to deallocate the memory when it is no longer needed.


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...