0

I am supposed to write a function that prints a sequence but in reverse order. It must return its parameter. The string should not be modified. I am only allowed to use the putchar function and while/if loops.

the function prototype is

char *revprint(char *strng)

so it should turn Hello into olleH

This is my code. Where am I wrong?

char *rev_print(char *strng)
{
    int i = 0;
    
    while (*strng[i] = '\0');
    {
        i++;
    }
    
    while (*strng[i] <= 0)
    {
        putchar(*strng[i])
        i--;
    }
    return (*strng)
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
Jonte
  • 11
  • 2
  • Please show your attempt, along with a `main` function that calls it, input,and output. – dbush Apr 30 '21 at 13:40
  • Welcome to Stack Overflow. You should show us the code that you tried and explain what it does wrong. Then we can help you fix it. – Adrian Mole Apr 30 '21 at 13:40
  • Please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). Please read our [Tour](https://stackoverflow.com/tour), [How to Ask](https://stackoverflow.com/help/how-to-ask), and [How do I ask and answer homework questions?](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions). – MikeCAT Apr 30 '21 at 13:46
  • SO is not a free-coding service. We won't provide full solution for homework dump without any effort shown. See also: [Why is "Can someone help me?" not an actual question? - Meta Stack Overflow](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) – MikeCAT Apr 30 '21 at 13:47
  • 1
    Your function is wrong in many points. There are many questions about reversing strings, so take a look at them. [Posts containing 'function reverse string' - Stack Overflow](https://stackoverflow.com/search?q=%5Bc%5D+function+reverse+string) – MikeCAT Apr 30 '21 at 13:51
  • 2
    aside from other problems there may be, your `while (*strng[i] = '\0');` loop has a semicolon at the end, meaning that it has no body. And are you really meaning to do an assignment in that loop? I'm guessing no since you say you're not supposed to modify `strng`. `=` is the assignment operator, `==` is the comparator. – yano Apr 30 '21 at 14:04
  • What about https://stackoverflow.com/questions/198199/how-do-you-reverse-a-string-in-place-in-c-or-c#5315651 ? – harper Apr 30 '21 at 14:22

1 Answers1

0

If you cannot change the original string, then you need to create a new one to return:

char *rev_print(const char *strng)
{
    int i = 0;
    int size_ = 0;
    char* reversed = calloc(strlen(strng), sizeof(char));

    while (strng[size_] != '\0')
    {
        size_++;
    }

    while (size_ > 0)
    {
        reversed[i++] = strng[--size_];
    }

    return reversed;
}

Just remember to free() the return of the function after you use it!

char* reversed = rev_print(original_string);
print(reversed);
free(reversed);