Problem printing out array using putchar function. Getting a punch of symbols as output

434 Views Asked by At
#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
1

There are 1 best solutions below

2
xhienne On

In print_rev(), during your first pass where you reinvent the strlen() wheel, you also increment s to point to the terminating NUL character.

In the last loop, you are reusing s as if it hadn't changed: s[arrLength] obviously point outside of your string since s points to the end of it.

Solution: change

for (; arrLength >= 0; arrLength--) {
    putchar(s[arrLength]);
}

to

for (; arrLength >= 0; arrLength--) {
    s--;
    putchar(*s);
}