This is my task:
Realize function that reverses null terminated string. The prototype of the function is void Reverse(char *ptr);. Do not use standard library functions.
This is my code for now:
void Reverse(char *ptr) {
char *newString;
char ch = *ptr;
unsigned int size = 0;
for (int i = 1; ch != '\0'; i++) {
ch = *(ptr + i);
size++;
}
newString = (char*)malloc(size);
for (int left = 0, right = size - 1; left < size; left++, right--) {
*(newString + left) = *(ptr + right);
}
printf("%s", newString);
printf("\n");
}
It reverses the string and saves it in the newString
My first problem is that when I print the newString to see if the functions works the string is reversed, but after it there are some symbols.
For example:
If I have char *str = "hello"; and Reverse(str); in the main method
the result of printf("%s", newString) will be olleh****.
But if change the
newString = (char*)malloc(size); to
newString = (char*)malloc(1); it works fine.
My second problem is that I don't know how to save the newString into the given one. I am using a new String because the given one can't be changed.
mallocdoesn't count as a standard library function?"james". If you swap the first and last characters, you get"samej". And if you swap the second and next-to-last, you get"semaj", which is the reversed string. I'll leave you the task of writing the loop to do that.