为什么交换功能不起作用?该程序在第一次交换调用中失败:
*ch1 = *ch2;
所有代码:
void swap(char *ch1, char *ch2);
void reverse(char *string);
int main() {
char *test_string = "abcd";
char *test_string1 = "abc";
reverse(test_string);
reverse(test_string1);
printf("%s %s", test_string, test_string1);
assert(strcmp(test_string, "dcba"));
assert(strcmp(test_string1, "cba"));
}
void reverse(char *string) {
for (int i = 0, j = (int) (strlen(string) - 1); i != j; ++i, --j) {
swap(&string[i], &string[j]);
}
}
void swap(char *ch1, char *ch2) {
char temp = *ch1;
*ch1 = *ch2;
*ch2 = temp;
}
输出:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)