Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
传递char*指针时出现分段错误_C_Pointers - Fatal编程技术网

传递char*指针时出现分段错误

传递char*指针时出现分段错误,c,pointers,C,Pointers,我试图制作一个程序,用递归检查输入的字符串是否是回文的。下面是下面的代码 #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); }

我试图制作一个程序,用递归检查输入的字符串是否是回文的。下面是下面的代码

#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;
}
#包括
#包括
int isPalindrome(字符*s、int i、int j){
如果(i>=j)
返回1;
如果(s[i]!=s[j])
返回0;
返回isPalindrome(s,i+1,j-1);
}
int main(){
字符*字;
printf(“输入单词”);
scanf(“%s”,单词);
if(isPalindrome(字,0,strlen(字)-1))
printf(“回文\n”);
其他的
printf(“非回文\n”);
返回0;
}
该程序似乎给出了由函数isAlindrome()引起的分段错误。我的代码哪里出错了


谢谢。

当您有一个字符指针时,您应该有另一个已分配的字符串,并使其指向该字符串

或者直接为字符串动态分配空间

如果malloc了一些空间,代码就会工作

char *word = malloc(20);
或者你可以创建一个字符串

char word[20];

scanf(“%s”,单词)
调用未定义的行为-您需要初始化指针
word
以首先指向有效(且足够)的内存您尚未为
word
分配内存--它只是一个指针。如前所述,没有为
word
分配内存,您可以更改它,例如
char-word[80]您是如何确定故障在
isPalindrome
内的?
scanf
应该先失败。@DrewDormann已修复。成功了!!谢谢。