Search code examples
cpointersremoving-whitespacememmove

Memmove in same pointer for deleting multiple whitespaces C


while this Code works:

 char * k = "asd"; 
 char * j = malloc(sizeof(char) * 3);
 memmove(j,k,3);
 printf("%s",j);

while code gives error:

 char * k = "asd";
 char * j = malloc(sizeof(char) * 3);
 memmove(k,k+1,3);
 printf("%s",k); // output should be "sd"

I am thinking wrong? Why it gives an erorr? I'm planning to use it for deleting the multiple whitespaces ("aaa.......bbb"(dots are spaces) -> "aaa bbb")

Thank you.


Solution

  • A declaration like

    char *k = "asd";
    

    causes the string literal to be stored in the read-only data segment. (C compilers tend to not warn for this case even though declaring the pointer as const char *k = "asd" would be safer, for historical reasons.)

    If you want the string contents to be modifiable, you will need to use an array instead, like

    char k[] = "asd";