#include <stdio.h>
void print_rev(char *s);
int main(void)
{
char *str;
str = "I do not fear computers. I fear the lack of them - Isaac Asimov";
print_rev(str);
return (0);
}
// read array and print it out backwards char by char.
void print_rev(char *s)
{
int arrLength;
arrLength = 0;
// capture length of array
while (*s != '\0') {
arrLength++;
s++;
}
arrLength--;
// print array backwards
for (; arrLength >= 0; arrLength--) {
putchar(s[arrLength]);
}
putchar('\n');
}
This is my code. When I run it, all I can do is get it to print out this output: picture of output
I tried researching why this happens but I can't find any videos where people use putchar and not printf. Much help appreciated.
The point of my code is to take the string and reverse it using putchar.
I cannot use the function strlen().
Expected output:
vomisA caasI - meht fo kcal eht raef I .sretupmoc raef ton od I
In
print_rev(), during your first pass where you reinvent thestrlen()wheel, you also incrementsto point to the terminating NUL character.In the last loop, you are reusing
sas if it hadn't changed:s[arrLength]obviously point outside of your string sincespoints to the end of it.Solution: change
to