我正在阅读 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
在这里更准确地描述:
比我更有知识和经验的人可以向我解释我的代码有什么问题,或者给我一个提示,告诉我为什么我会遇到这个令人沮丧的错误?