The error is here:
while (*sPtr != '\0') {
++length;
++sPtr;
}
At this point the sPtr point at the end of the string so in the second loop it never decrement.
for (int i = length; i >= 0; --i) {
printf("%c", *(sPtr+1));
}
A possible solution can be this:
for (int i = length; i >= 0; --i) {
printf("%c", *(sPtr));
--sPtr;
}
Answer from Zig Razor on Stack OverflowSo i just got to pointers in the K&R C programming book and one of the challenges is to rewrite the functions we worked on previously and implement pointers. i am trying to understand the topics as well as i can before moving forward in the book so if you guys could tell me the best practices and what i should have done in this snippet of code i would greatly appreciated. for reference i was thinking about how i see temp numbers like i used less and less in replacement of ( ; check ; increment ). sorry if this post seems amateur.
#include <stdio.h>
#include <string.h>
void reverse(char *s) {
char temp[20];
int len = strlen(s);
s += len - 1;
int i = 0;
while (len--) {
temp[i++] = *s--;
}
temp[i] = '\0'; // Null-terminate the reversed string
printf("%s\n", temp); // Print the reversed string
}
int main(void) {
char string[20] = "hello world";
reverse(string);
return 0;
}
#include <stdio.h>
#include <string.h>
void reverse(char *s) {
char temp[20];
int len = strlen(s);
s += len - 1;
int i = 0;
while (len--) {
temp[i++] = *s--;
}
temp[i] = '\0'; // Null-terminate the reversed string
printf("%s\n", temp); // Print the reversed string
}
int main(void) {
char string[20] = "hello world";
reverse(string);
return 0;
}Videos
The error is here:
while (*sPtr != '\0') {
++length;
++sPtr;
}
At this point the sPtr point at the end of the string so in the second loop it never decrement.
for (int i = length; i >= 0; --i) {
printf("%c", *(sPtr+1));
}
A possible solution can be this:
for (int i = length; i >= 0; --i) {
printf("%c", *(sPtr));
--sPtr;
}
This is the solution I came up with. Thanks for the help anyone provided!
while (*sPtr != '\0') {
++length;
++sPtr;
}
printf("Reverse string = ");
sPtr = sentence;
for (int i = length; i >= 0; --i) {
printf("%c", *(sPtr+length));
--sPtr;
}