0
#include<stdio.h>
void squeeze(char *s1,char *s2);

main()
{
    char *s1="string";
    char *s2="spring";
    squeeze(s1,s2);
    printf("%s",s1);
}

void squeeze(char *s1,char *s2)
{
    int i=0,j=0,k=0,bool=1;
    for(i=0,k=0;s1[i]!='\0';i++)
    {
      for(j=0;s2[j]!='\0';j++)
        if(s1[i]==s2[j])
        {
           bool=0;
           break;
        }
     if(bool)
     {
         s1[k++]=s1[i];
     }
     bool=1;
    }
    s1[k]='\0';
}

this program gave me a seg fault.i tried debugging it with gdb. the error is in line 25 (i.e) s1[k++]=s1[i];

i tried running the same function in java. suprisingly it was working well.i replaced the pointers with arrays and exit the loop when the looper is equal to array length.but it wont work on c any suggestions? thanks

programer8
  • 567
  • 1
  • 6
  • 17
  • 1
    This code is a good example of why `i`, `j` and `k` are bad variable names. It's super hard to tell what's what here. `bool` is a particularly bad variable name, as it only conveys the type of the variable, not its purpose. – user229044 Sep 25 '13 at 01:47

1 Answers1

1

You are trying to modify a string literal. A string literal is a constant read-only string in C. You cannot change it in any way. Try declaring the string as a char array.

char s1[] = "string";
char s2[] = "spring";
Sarat
  • 113
  • 1
  • 1
  • 7
  • that worked.i thought char s1[] and char *s1 are similar.both create pointers to an array. – programer8 Sep 25 '13 at 01:52
  • NO. Check this link: http://stackoverflow.com/questions/4680431/memory-allocation-char-and-char – Sarat Sep 25 '13 at 01:54
  • Similar, yes, identical no. They both create pointers to an array but `char *xyzzy = "plugh"` creates a pointer to an array you're not allowed to modify. `char xyzzy[] = "plugh"` creates a new array which you _can_ modify, then gives you a pointer to it. – paxdiablo Sep 25 '13 at 01:57
  • and what happens if i use a volatile modifier to the declaration? – programer8 Sep 25 '13 at 02:17
  • 'volatile' doesn't change the result. You are getting a seg fault because you are accessing memory you are not supposed to access or accessing it in a way it should not be accessed. 'volatile' keyword is essentially used to avoid compiler optimization. It is in any way not related to your problem here. – Sarat Sep 25 '13 at 02:29