传递 char* 指针时出现分段错误 [英] segmentation fault in passing a char* pointer

查看:84
本文介绍了传递 char* 指针时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个程序,该程序使用递归检查输入的字符串是否为回文.这是以下代码.

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;
}

程序似乎给出了由函数 isPalindrome() 引起的分段错误.我的代码哪里出错了?

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

谢谢.

推荐答案

当你有一个字符指针时,你应该有另一个已经分配的字符串并让它指向那个

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];

这篇关于传递 char* 指针时出现分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆