嗨,我是 C 世界的新手,我的代码确实有些奇怪。目标是创建一个函数,可以在开头和结尾处用空格和/或制表符修剪字符串。我无法使用字符串库。
问题是我的代码中有一个 printf 只是用于测试,它的工作非常好。但是,如果我删除该 printf,该功能将无法正常工作...有人可以帮助我吗?
代码如下:
#include <stdio.h>
short trim(short idx,char*str,short dir){ //gives the index to trim
while(*(str+idx)==' ' || *(str+idx)=='\t')
idx+=dir;
return idx;
}
short findEnd(char *str){ // find the end of the string
int ret=0;
while(*(str+ret)!='\0')ret++;
return ret-1;
}
char *strtrim(char *str){ //The function that trims the string
short begin=trim(0,str,1);
short end=trim(findEnd(str),str,-1)+1;
char ret[end-begin];
for (short i=begin; (i-begin)<sizeof(ret);i++){
ret[i-begin]=*(str+i);
printf("%d\n",i);// <--------------------------------this is the printf
}
char *c=&ret[0];
return c;
}
int len(char *str){// return the length of the given string
int ret=0;
for(int i=0;*(str+i)!='\0';i++){
printf("%d %c\n",i,*(str+i));// another printf for testing porpuses
ret=i;
}
return ret;
}
int main(){
char *str=" this is a great test to test your testing skills ";
printf("%d\n",len(strtrim(str)));
}
仅仅一个 printf 怎么能产生如此大的差异?如果我每次运行时都使用 printf,它会给我相同且正确的输出,但是如果我不使用 printf,它每次运行时都会给我一个完全不同的输出,而且总是错误的输出
最佳答案
在strtrim
中,您使用char ret[end-begin];
来分配返回指针值。
这是本地内存,没有适当的生命周期:一旦退出例程,它就可供程序的其他部分使用:未定义的行为。
“当我插入/删除 printf
时它会起作用”应该是此类错误的危险信号。
您可以像这样修复它:
- 使用
strdup
返回实际分配的结果副本 - 传递另一个参数以供例程填充
由于您无法更改函数原型(prototype),因此只需在函数内部分配即可。如果您无法使用 strdup
或任何复制功能,您仍然可以这样做。
替换该代码:
char ret[end-begin];
通过以下方式:
char *ret = malloc(end-begin);
然后返回 ret
而不是 c
。
您现在已经分配了一个字符串,当您不再需要它时,请不要忘记在调用者中释放
它。
关于C:带有 printf 的代码与没有 printf 的代码的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43019646/