-1

I am trying to make a program which checks whether the entered string is palindrome or not using recursion. Here is the following code.

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

int isPalindrome(char* s, int i, int j) {
    if (i >= j)
        return 1;

    if (s[i] != s[j])
        return 0;

    return isPalindrome(s, i+1, j-1);
}

int main() {

    char* word;
    printf("Enter a word \n");
    scanf("%s", word);

    if (isPalindrome(word, 0, strlen(word) - 1))
        printf("Palindrome \n");
    else
        printf("Not Palindrome \n");

    return 0;
}

The program seems to give a segmentation fault caused by the function isPalindrome(). Where is my code going wrong?

Thank you.

Barmar
  • 741,623
  • 53
  • 500
  • 612
AribAlam
  • 27
  • 3

1 Answers1

0

When you have a character pointer, You should either have another character string which has been allocated and make it point to that

OR you directly dynamically allocate space for a string.

Your code works if you malloc some space

char *word = malloc(20);

or you can just create a string

char word[20];
Shaun F
  • 85
  • 1
  • 2
  • 8