C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Dynamic string input

C Program: Dynamic string input

C

#include <stdio.h>

#include <stdlib.h>

 

int main() {

    char *str;

    int size;

 

    // Step 1: Get maximum string size from user

    printf("Enter maximum length of the string: ");

    scanf("%d", &size);

 

    // Step 2: Dynamically allocate memory for string

    str = (char*) malloc((size + 1) * sizeof(char)); // +1 for '\0' (null terminator)

 

    if (str == NULL) {

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

        return 1;

    }

 

    // Step 3: Clear input buffer

    getchar();

 

    // Step 4: Take string input

    printf("Enter a string: ");

    fgets(str, size + 1, stdin);

 

    // Step 5: Display the string

    printf("\nYou entered: %s", str);

 

    // Step 6: Free allocated memory

    free(str);

 

    return 0;

}

Output

 
OUTPUT :
Enter maximum length of the string: 30
Enter a string: IT Developer creates e-learning tools
You entered: IT Developer creates e-learning tools

Explanation

Step

Description

malloc()

Allocates memory for the string based on user input.

fgets()

Safely reads a string including spaces.

getchar()

Clears newline from input buffer before fgets().

free(str)

Frees dynamically allocated memory after use.