【发布时间】:2017-12-17 07:01:42
【问题描述】:
我编写了一个函数,当我运行它时它运行良好,但是当我用不同的输入多次运行它时出现问题。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#define MAX_SIZE 20
int SumStr(char *str) {
int i = 0, j = 0, num = 0, tempnum = 0;
char temp[MAX_SIZE];
while (*(str + i) != 0) { //While not NULL - Checked
while (((*(str + i)) >= 48) && ((*(str + i)) <= 57)) { //while str[i] is [0-9]
*(temp + j) = *(str + i);
++j; ++i;
}
if (j != 0) {
tempnum = atoi(temp);
num = tempnum + num;
tempnum = 0;
j = 0;
}
++i;
}
return num;
}
void Test3(char *arr, int sum)
{
int tempSum = SumStr(arr);
if (tempSum != sum)
{
printf("Your Output is %d, Expected: %d (-3)\n", tempSum, sum);
}
}
void main() {
Test3("ax3b5mt11f", 19);
Test3("5$5$5", 15);
Test3("1234", 1234);
Test3("1$0!100", 101);
Test3("1$1!1", 3);
}
该函数的目的是对字符串中的所有数字求和。
当我用这个 main 运行一次函数时(例如),它运行良好;
void main() {
Test3("1$0!100", 101);
}
Output: num=101
但是当 main 用不同的输入多次运行函数时,输出完全错误。
这个main的输出;
void main() {
Test3("ax3b5mt11f", 19);
Test3("5$5$5", 15);
Test3("1234", 1234);
Test3("1$0!100", 101);
Test3("1$1!1", 3);
}
是;
Your Output is 6871, Expected: 15
Your Output is 6718, Expected: 1234
Your Output is 5024, Expected: 101
【问题讨论】:
-
除非你的任务是尽可能写出最模糊的代码,否则
((*(str + i)) >= 48) && ((*(str + i)) <= 57)真的应该是(s[i] >= '0' && s[i] <= '9') -
或者,比明确的范围更好,使用来自
<ctype.h>的isdigit()。 -
实际上,我正在使用指针进行测试,这就是这段代码写成这样的原因。此外,我不能使用 ctype.h,我只能使用我在代码中已经提到的库。谢谢!
-
不,这个任务不会强迫你写出这种可憎的东西。您可以随时添加一个临时的
char c = *(str + i);。无论您的任务标准如何,与幻数的比较都是不可原谅的。 -
@StoryTeller 我完全同意这段代码很糟糕。感谢 cmets!
标签: c function memory-leaks