I have a problem with this function. I am trying to remove trailing whitespace from a pointer of type char*.
Something like that:
char *ptr = "Soy un puntero dinámico y me sobran espacios al final ";
With the difference that this one is static and the one I am handling is dynamic.
I was doing this function for it but for some reason that I can't see, the while is not working for me, that is to say that the value of c is c=0; when I should be older.
char *quita_espacios_al_final(char **s)
{
char *p = *s;
if(p==NULL)return NULL;
unsigned int i=strlen(p);
unsigned int k=i;
unsigned int c=0;
while( *(p+i)==' ' && i>0)
{
i--;
c++;
}
char *tmp = new char [k-c+1];
for(unsigned int j=0; j<k-c; j++)
*(tmp+j)=*(p+j);
delete [] p;
return tmp;
}
Any ideas why it doesn't work? o Another alternative to count whitespace at the end of the string? PS: I don't care if it's in C or C++ as long as it works, but I can't change the type, it has to be (char*).
If we assume a chain such that:
we'll find that
And if we look at the location of the different elements in memory we have the following:
That is, the position
6
corresponds to a null character.This comes because of the following line:
where
i
, initially, isstrlen(p)
...... try subtracting 1 from
i
: