C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Reverse string using dynamic memory

C Program: Reverse string using dynamic memory

C

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

 

int main() {

    char *str, *rev;

    int len, i;

 

    // Step 1: Input string length

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

    scanf("%d", &len);

 

    // Step 2: Allocate memory dynamically

    str = (char*) malloc((len + 1) * sizeof(char));

    rev = (char*) malloc((len + 1) * sizeof(char));

 

    if (str == NULL || rev == NULL) {

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

        return 1;

    }

 

    // Step 3: Clear input buffer

    getchar();

 

    // Step 4: Input string

    printf("Enter a string: ");

    fgets(str, len + 1, stdin);

 

    // Remove trailing newline if present

    str[strcspn(str, "\n")] = '\0';

 

    // Step 5: Reverse string manually

    int str_len = strlen(str);

    for (i = 0; i < str_len; i++) {

        rev[i] = str[str_len - i - 1];

    }

    rev[str_len] = '\0';

 

    // Step 6: Display reversed string

    printf("\nOriginal String: %s", str);

    printf("\nReversed String: %s", rev);

 

    // Step 7: Free memory

    free(str);

    free(rev);

 

    return 0;

}

Output

 
OUTPUT :
Enter maximum length of the string: 30
Enter a string: IT Developer
Original String: IT Developer
Reversed String: repoleveD TI

 

Explanation

Step

Description

malloc()

Allocates memory dynamically for both original and reversed strings.

fgets()

Reads string safely including spaces.

strcspn()

Removes newline character added by fgets().

for loop

Reverses the string manually by iterating from the end.

free()

Releases allocated memory after use.