Hi i'm new in the world of C and there is something really odd about my code. The objective is to create a function that can trim a string with spaces and/or tabs at the beginnig and at the end. I cannot use String lib.
The problem is that there is a printf in my code just for testing and it does the job very well. But if i delete that printf the function doesn't work properly... Anyone can help me please?
Here's the code:
#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)));
}
How can just a printf makes such a difference? If i use printf everytime i run it gives me the same and the correct output, however if i don't use the printf it gives me a totally different output eveytime i run it and it's always the wrong one