Complementary task for topic: 7
M Nemeth · 2023-08-29 15:21:04.624218'
DStrings: Reversed Dynamic String
DStrings: Reversed Dynamic String
Create a C program that reads a string from the user and creates a dynamic string that contains the reversed version of the input string. The program should allocate memory dynamically to hold the reversed string.
Hint: Use dynamic memory allocation to create the reversed dynamic string.
Prompt the user to enter a string.
Reverse the input string and store it in the dynamic string.
Display the reversed dynamic string as the output.
Deallocate the memory used by the dynamic string.
Solution
#include
#include
#include
int main() {
char* dynamicString = NULL;
char inputString[200];
printf("Enter a string: ");
scanf("%199[^\n]", inputString); // Limit the input to 199 characters and exclude newline
int length = strlen(inputString);
// Allocate memory for the reversed dynamic string
dynamicString = (char*)malloc((length + 1) * sizeof(char)); // +1 for null terminator
if (dynamicString == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
// Reverse the input string and store it in the dynamic string
for (int i = 0; i < length; i++) {
dynamicString[i] = inputString[length - 1 - i];
}
dynamicString[length] = '\0'; // Null-terminate the reversed string
// Print and use the reversed dynamic string
printf("Reversed string: %s\n", dynamicString);
// Deallocate the memory used by the dynamic string
free(dynamicString);
return 0;
}
Explanation
The program defines a character pointer dynamicString to hold the reversed dynamic string and a character array inputString to store the user input for the original string. The length of the input string is calculated using strlen(). Memory for the reversed dynamic string is allocated using malloc(), based on the length of the input string plus one extra character for the null terminator. The program then iterates through each character of the input string and stores its reversed version in the dynamic string. The reversed dynamic string is null-terminated by adding the null character at the end. The reversed dynamic string is printed using printf(). Finally, the memory used by the dynamic string is deallocated using free() to avoid memory leaks.