0

I am trying to initialize s1 with the value and later in squeeze() . I am changing s1. Pointer initialization throws a seg fault but array version works fine. Could someone tell me If i can do it with the pointer version and what is wrong with this ? may be because i have not used malloc ??

int main() {

        char s1[] = "xyz abc zzz" ; // this works fine.
      // char *s1 = "xyz abc zzz"; // if i initialize like this it throws a seg fault. 

         char *s2 = "abx xxx xxx" ;
        squeeze(s1,s2) ;
        puts (s1) ;
        return 0 ;

}

void squeeze(char *s1, char *s2 ) {

        int i , j, k = 0;

        for (i=0 ; s1[i] != '\0' ; ++i) {

                for (j=0; s2[j] != '\0'; j++) {
                        if (s2[j] == s1[i])
                                break;


                }
           if(s2[j] == '\0')

                s1[k++] = s1[i] ;

        }

        s1[k++] = '\0' ;

}
Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
Ajay Mishra
  • 383
  • 3
  • 6
  • 4
    This has been asked *hundreds* of times on SO, [this being one such question](http://stackoverflow.com/questions/10252177/what-is-wrong-with-below-code) – WhozCraig Aug 24 '13 at 20:11
  • Read: [Difference between `char *str` and `char str[]` and how both stores in memory?](http://stackoverflow.com/questions/15177420/what-does-sizeofarr-return/15177499#15177499) – Grijesh Chauhan Aug 24 '13 at 20:12
  • 1
    You can't modify a constant because it's ... well ... constant. You can modify a variable because it's ... you get the idea. – David Schwartz Aug 24 '13 at 20:12
  • The second is not valid C++11 (and deprecated before that). – chris Aug 24 '13 at 20:12

1 Answers1

3

The difference is:

Declaration:

char s1[] = "xyz abc zzz" ; 

Creates an array of size strlen(RHS) + 1 and is modifiable. In second form

char *s1 = "xyz abc zzz"; 

s1 is a pointer to a string literal which is in an unmodifiable memory area; hence modification of the string is illegal operation.

user1952500
  • 6,611
  • 3
  • 24
  • 37