Do not modify original string in a function

Question:

I made a function to find out if two words are anagrams … But I didn't want to modify the original two strings. And my function modifies one of the strings, the string that I sAux in an auxiliary char * ( sAux ) (I just did it so as not to modify the original string). To my understanding, the auxiliary pointer is pointing to the same place as the pointer that arrives as a parameter to the function (the one of the string that I don't want to modify). But I can't think of how to fix it.

I show you the function. The string that is modified for me is the call s1 ( const char*s1 -parameter that receives the function). Notably, I must not modify the original strings and must use pointer arithmetic.

int esAnagrama(const char *s1, const char *s2)//s1 se modifica
{
char*sAux=(char*)s1,*s2Aux=sAux;//puedo observar que apuntan a lo mismo- a la misma direccion de memoria.
int i=0,j=0,k=0;
while(*(sAux+i)&&*(s2+k))
{
    if((*(sAux+i)!=*(s2+k))&&*(s2+k)!=' '&&*(sAux+i)!=*(s2+k)+32&&*(sAux+i)!=*(s2+k)-32)
       {
        if(*(sAux+i)!=' ')
        {
            *(s2Aux+j)=*(sAux+i);///si no encontro la letra la dejo en s2aux
            j++;
        }
       }
        else k++;//si encontro la letra sigo recorriendo la cadena
    i++;
    if(*(sAux+i)=='\0'&&i!=j)
    {
        *(s2Aux+j)='\0';
        sAux=s2Aux;
        i=j=0;
    }
}
return(!*(s2+k)&&!*(sAux+i));
}

Any suggestions on how to fix it so that s1 , original string, is not modified? I tried to reserve memory for the char* in which I under the original string but it gave the result you expected.

Answer:

Easy, create a temporary string inside the function:

int esAnagrama(const char *s1, const char *s2)
{
  char* temporal = (char*)malloc(strlen(s1)+1 * sizeof(char));
  strcpy(temporal,s1);

  // trabajas con temporal en vez de con s1
  char*sAux=temporal,*s2Aux=sAux;

  // ...

  int to_return = !*(s2+k)&&!*(sAux+i);
  free(temporal);

  return to_return;
}
Scroll to Top