Problem removing blanks at the end of a char type pointer *

2

I have a problem with this function. I'm trying to eliminate blank spaces at the end of a char * pointer.

Something like this:

char *ptr = "Soy un puntero dinámico y me sobran espacios al final       ";

With the difference that this is static and the one I am driving is dynamic.

I was doing this function for it but for some reason I can not see, the while is not working for me, meaning that the value of c is c = 0; when it should be higher.

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 idea why it does not work? o Another alternative to count the blank spaces at the end of the chain? PS: I do not care if it's in C or in C ++ while it's working, but the guy can not change it, it has to be (char *).

    
asked by Iván Rodríguez 12.06.2018 в 14:23
source

1 answer

2

If we assume a string such that:

char *ptr = "hola  ";

We will find that

strlen(ptr) == 6

And if we look at the location of the different elements in memory we have the following:

0x00 0x01 0x02 0x03 0x04 0x05 0x06
  h    o    l    a    _    _   
while( *(p+i)==' ' &&  i>0)

That is, the position 6 corresponds to a null character.

This comes on the occasion of the following line:

unsigned int i=strlen(p);
if( i > 0 )
  i--;

where i , initially, is worth strlen(p) ...

... try subtracting 1 to i :

char *ptr = "hola  ";
    
answered by 12.06.2018 / 14:44
source