我正在阅读 K&R C,主要是为了刷我的 C 技能,并且在尝试编写一个程序来反转给定的字符串时,我遇到了一个困扰我的错误,最糟糕的是,我无法调试 - 也不知道可能是什么原因。
我的代码如下:
#include <stdio.h>
#include <string.h>
char * reverse(char *string);
int main(int argc, char *argv[])
{
printf("Please input a string: \t");
char string[256];
scanf("%s", string);
char *reversed = reverse(string);
printf("The reversed string is %s\n", reversed);
return 0;
}
char * reverse(char string[])
{
int size = strlen(string);
printf("DEBUG: The size of the string that we got as input was: %d\n", size);
int counter;
char reversed[size + 1];
for(counter = size - 1; counter >= 0; counter--) {
reversed[size - counter] = string[counter];
printf("DEBUG: The character copied now was %c and was at index %d\n", string[counter], counter);
}
reversed[size + 1] = '\0';
printf("DEBUG: The reversed string is %s\n", reversed);
return reversed;
}
(请原谅乱七八糟的调试语句。除此之外,随时纠正您可能看到的任何错误,也随时提出改进建议)
现在,我的代码可以正常工作(大部分),但错误是它复制了我没有输入的字符。以下是两次测试运行的(有趣的)结果:
第一个:
nlightnfotis@crunchbang:~/SoftwareExperiments$ ./reverse
Please input a string: fotis
DEBUG: The size of the string that we got as input was: 5
DEBUG: The character copied now was s and was at index 4
DEBUG: The character copied now was i and was at index 3
DEBUG: The character copied now was t and was at index 2
DEBUG: The character copied now was o and was at index 1
DEBUG: The character copied now was f and was at index 0
DEBUG: The reversed string is $sitof
The reversed string is $sitof
(注意 $
)
第二个:
nlightnfotis@crunchbang:~/SoftwareExperiments$ ./reverse
Please input a string: lol
DEBUG: The size of the string that we got as input was: 3
DEBUG: The character copied now was l and was at index 2
DEBUG: The character copied now was o and was at index 1
DEBUG: The character copied now was l and was at index 0
DEBUG: The reversed string is lol
The reversed string is lol
此处描述更准确:
比我更有知识和经验的人可以向我解释我的代码有什么问题,或者给我一些提示,说明为什么我会遇到这个令人沮丧的错误吗?
最佳答案
你正在返回一个局部变量:
char * reverse(char string[]) {
char reversed[size + 1];
....
return reversed;
}
分配在堆栈上的局部变量 reversed
在函数 reverse
返回后不复存在。因此 main
对它的任何引用都会导致未定义的行为。
要解决此问题,您可以执行以下任一操作:
使函数
void
并修改输入数组。将数组
reversed
声明为静态的,以便其生命周期更改为程序的生命周期。动态分配(然后取消分配)
反向
关于c - C 中的字符串反转 : What is it I am doing wrong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16112124/