C EXC_BAD_ACCESS使用字符串操作

时间:2018-02-19 23:39:16

标签: c string

尝试运行我的函数来反转字符串时,我得到一个EXC_BAD_ACCESSS。我不知道这是Xcode问题还是编码。

代码:

char *reverse(char *input, int left, int right) {
    if(left>=right)
        return input;

    char temp = input[left];//sets temp = to rightmost
    input[left]=input[right];//swaps front with back
    input[right]=temp;//swaps back with front
    reverse(input, left+1, right-1);

    return "";
}

1 个答案:

答案 0 :(得分:0)

如果传递常量字符串,程序将崩溃,因为input[left] = input[right]是非法的。对于递归调用,您必须在函数中调用函数:

#include <stdio.h>
#include <stdlib.h>

char *reverse(char *input, int left, int right) {

    if(left>=right)
        return input;

    char temp = input[left];//sets temp = to rightmost

    input[left] = input[right];//swaps front with back

    input[right] = temp;//swaps back with front

     return(reverse(input, left+1, right-1));
 }

int main(void)
{
    char str[] = { '1', '2', '3', '4', '5', '6', '7', 0 };

    char *r =  reverse(str, 0, 6);

    printf("RSTR: %s",r);

    return 0;
}

输出:

RSTR: 7654321