【发布时间】:2017-01-17 01:43:22
【问题描述】:
我的测试用例将垃圾写入结果变量时遇到问题。我对 C 很陌生,所以我无法确定是什么原因造成的。
//Author: Ryan Fehr
//Contributors:
#include <stdio.h>
#include <string.h>
int remover(char[], char[], char[]);
int remover(char source[], char substring[], char result[])
{
char *current = source;
// printf("%s n", current);
char *currentSub = substring;
//printf("%c n", *currentSub);
int i = 0;
while(*current != '\0')//Loops through the source string
{
//Uncommenting the line below will show you the comparisons being performed
printf(" %c | %c \n", *current, *currentSub);
if(*current == *currentSub || *currentSub == '\0')//True when a letter matches with a letter in the subStr or the complete subStr was found
{
if(*currentSub == '\0')
{
char pre[((current-(i) - source))];//Stores everything before the subString in pre(current-i) - source
memcpy(pre, source, (current-i) - source);
printf("Pre: %s\n",pre);
//Counts how many chars are after the substring
int n = 0;
while(*current != '\0')
{
n++;
current++;
}
char post[n];//Stores everything after the subString in post
memcpy(post, current-n, n);
printf("Post: %s\n",post);
strcat(result, pre);
strcat(result,post);
printf("Substring removed: %s\n", result);//Prints the value after substring has been removed
return 1;
}
i++;
currentSub++;
}
else
{
i=0;
currentSub = substring;
}
current++;
}
return 0;
}
int main(void)
{
//TEST 1
char s[] = "jump_on_down_to_getfart_and_up_to_get_down_";
char sub[] = "fart";
char r[100] = "";
printf("Test 1:\n");
printf("Source: %snSubstring: %s\n",s,sub);
printf("%d\n\n", remover(s, sub, r));
//EXPECTED OUTPUT: 1
//TEST 2
strcpy(s, "racecar");
strcpy(sub, "x");
strcpy(r, "");
printf("Test 2:n");
printf("Source: %snSubstring: %s\n",s,sub);
printf("%d\n\n", remover(s, sub, r));
//EXPECTED OUTPUT: 0
//TEST 3
strcpy(s, "jump on down to get and up to get down ");
strcpy(sub, "up");
strcpy(r, "");
printf("Test 3:n");
printf("Source: %snSubstring: %s\n",s,sub);
printf("%d\n\n", remover(s, sub, r));
//EXPECTED OUTPUT: 1
}
这是 Test1 输出的屏幕截图,如您所见,我得到了额外的垃圾打印,我认为我的数学对我的子字符串是正确的,所以我不确定是什么原因造成的。
【问题讨论】:
-
1)
strcat(result, pre);:result没有足够的空间。 -
在标准 C 中,不允许在其他函数中包含函数定义;将这些定义移出
main是个好主意
标签: c memory-management pointers