MrStove
MrStove

Reputation: 13

Setting last character in a string to 0 causes program crash

This is for a homework assignment, so it can not use loops of any kind as a way to force recursion practice. I am also not to change the method signature, or anything in the main() function.

The function is intended to use recursion to print a string in reverse. I learned on this site (Strip first and last character from C string) how to remove the last character in a string. When I try and reproduce it in my code, the program crashes on execution. Here is that code:

#include <stdio.h>
#include <string.h>

void print_reverse_str(char *str) {
    if (strlen(str) == 1) 
        printf("%c", &str[0]);
    else {
        int len = strlen(str);
        int lastIndex = len - 1;
        char endChar = str[lastIndex];
        printf("%c", &endChar);
        str[lastIndex] = 0;
        print_reverse_str(str);
    }
}

int main() {
    print_reverse_str("My string");
    printf("\n");
    print_reverse_str("!ti tog uoy ,siht daer nac uoy fI");
    printf("\n");
}

Upvotes: 1

Views: 200

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40155

  1. You can not change a string literal.
  2. Character display with printf. E.g printf("%c", character);, not &character

try this.

#include <stdio.h>
#include <string.h>

void print_reverse_str(char *str){
    if (*str){
        print_reverse_str(str+1);
        printf("%c", *str);
    }
}

int main(){
    print_reverse_str("My string");
    printf("\n");
    print_reverse_str("!ti tog uoy ,siht daer nac uoy fI");
    printf("\n");
}

Upvotes: 3

Related Questions