-1

in the below code:

using namespace std;

void swap(char *x,char *y){

  char tmp = *x;
  *x = *y;
  *y = tmp;

}

int main(){

 char a[]="ab";
 //char *a ="ab";

 swap( (a+0),(a+1) );
 cout<<a;

 return 0;
}

when the array a is initialized as a[]="ab", the swap function works, but when it is initialized as *a="ab", it throws segmentation fault, can anyone say why?

avaj
  • 95
  • 1
  • 1
  • 6
  • 5
    Turn up the warnings in your compiler. If using gcc/clang use `-pedantic-errors`. `char *a ="ab";` should not compile. – NathanOliver Mar 11 '19 at 15:36
  • 1
    This is for C but works well for this. Hesitant to hammer though: https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha – NathanOliver Mar 11 '19 at 15:40

2 Answers2

3

char a[]="ab"; is a local non-const array. You can modify non-const arrays.

String literals are const. When you initialise a pointer to a string literal, it points to a const object. The behaviour of modifying const object is undefined.

Even the initialisation char *a ="ab"; is ill-formed (since C++11), because a string literal doesn't implicitly convert to pointer to non-const char.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

This is pure C concept, read 5.5 Character Pointers and Functions in The C Programming Languages, you will know the answer. The problem is you cannot change a string constant.

cso
  • 91
  • 9