Complementary task for topic: 6
M Nemeth � 2023-08-29 15:21:04.627218'
Pointers: Reversing a String using Pointers
Pointers: Reversing a String using Pointers
Create a C program that reverses a given string using pointers and a separate function.
Hint: Define a function reverseString that takes a character pointer (pointing to the first character of the string) as an argument.
The function should reverse the characters of the string in-place.
In the main function, define a character array str and initialize it with some string.
Print the original string before calling the reverseString function.
Call the reverseString function, passing the address of the first character of the string.
Print the reversed string after calling the reverseString function.
Solution
#include
#include
void reverseString(char* str) {
int length = strlen(str);
char* start = str;
char* end = str + length - 1;
while (start < end) {
char temp = *start;
*start = *end;
*end = temp;
start++;
end--;
}
}
int main() {
char str[] = "Hello, World!";
printf("Original String: %s\n", str);
reverseString(str); // Pass the address of the first character of the string
printf("Reversed String: %s\n", str);
return 0;
}
Explanation
In this task, we define a reverseString function that takes a character pointer str as an argument. We first calculate the length of the string using strlen function and store it in the length variable. We define two character pointers start and end, pointing to the first and last characters of the string, respectively. Inside the while loop, we use pointer arithmetic to swap the characters pointed by start and end. We increment start and decrement end to move towards the center of the string. The loop continues until start is less than end, effectively reversing the characters in-place. In the main function, we have a character array str with initial value "Hello, World!". We print the original string before calling the reverseString function using printf(). We call the reverseString function, passing the address of the first character of the string. After the reversal, we print the reversed string using printf() to observe the change.