I've seen a lot of programs that trims leading and trailing whitespaces using C. Now, Im testing my knowledge in pointers. I want to create my own programs that trims whitespaces. I have no issue creating the part that trims theleading whitespaces. My question now is why does the code that I create for removing the trailing whitespaces not working ? Please take note of the question, why.
char * str = calloc(2000,sizeof(1));
char * modStr = calloc(2000,sizeof(1));
int start, i, end;
strcpy(str," test ");
int len = strlen(str);
i=0;
while(isspace((int) *str)!=0){
if(i>=len)
break;
printf("%d\n",i);
i++;
str++;
}
printf("first str:%s",str);
start = i;
i = strlen(str);
strcpy(modStr, str);
i=strlen(modStr);
--modStr;
while(isspace( *modStr)!=0){
if(i==0)
break;
printf("%d:%c\n",i,*modStr);
i--;
--modStr;
}
*modStr = 0;
I was able to remove the trailing whitespaces but when I try to print the string, it is empty. Could you tell me what's wrong?
char * str = calloc(2000,sizeof(1));I think this is creating an 8000 character buffer, not 2000. You should also take care not to let the user overflow this for you, e.g. by restricting the length of the strcpy.calloc(). You cannotfree()those later, unless you keep the original start addresses.