这是来自K和R的问题。当我尝试对其进行编译时,它会显示分段错误(核心已转储)。我似乎找不到错误。

#include <stdio.h>


这是您的基本交换

 void swap(char s[], int i, int j) {
    char temp;
    temp = s[i];
    s[i] = s[j];
    s[j] = temp;
}


void reverse(char s[]){
    int i, j;

    if (i == 0)
        j = strlen(s)-1;
    swap(s, i, j);
    j--;
    i++;
    // Here is where the problem arises. When i don't call the function here the program works perfectly  (The limitation being only the first and last char get swapped) otherwise it gives an error saying segmentation fault
    if (i < j)
        reverse(s);
}

int main () {
    int i;
    char s[10] = "hello";
    reverse(s);
    printf("%s", s);
}

最佳答案

首先,在i中声明reverse时,您没有为其分配值,因此其值将是随机的。因此,当您在比较中使用i时,这是未定义的行为。

09-04 16:47
查看更多