Hi, while I was looking at a program in my textbook, i encountered this program to reverse a string using recursive procedure-

#include <stdio.h>
int main(void)
{
    void rev();
    printf("Enter a line of text:\n");
    rev();
}
void rev()
{
    char c[20];
    if((c==getchar())!='\n')
    rev();
    putchar(c);
}

I couldn't quite understand the logic the author used, so I went to check the program on my pc which gave the error-

Runtime error(Exit status:139(Invalid memory reference))

What's this error about? and Is the program in textbook wrong?

Either the example contained an error or you entered it improperly. It should read

int main(void)
{
    void rev();
    printf("Enter a line of text:\n");
    rev();
}
void rev()
{
    char c;
    if((c=getchar())!='\n')
    rev();
    putchar(c);
}

Simply put, rev keeps calling itself to input a new char until it finds a newline. Each new char is pushed onto the stack. When it finds a newline it prints each char on the top of the stack until the stack is empty. Work through it by hand (maintaining your own stack) and you will see how it reverses the string.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.