-3
char a[] = {'t' , 'e' , 's' , 't' , 'i' , 'n' , 'g'};
sort(a,a+7);

This works absolutely fine.

char*a = "testing";
sort(a, a+7);

This fails to run. why is it not being sorted?

string a = "testing";
sort(a.begin(),a.end());

This works fine..

string a ="testing";
sort(a , a+7);

But this fails. Here 'a' is a C++ string but why is it necessary to use iterators here ?

  • 10
    Attempting to modify storage occupied by a string literal exhibits undefined behavior. – Igor Tandetnik Jun 27 '16 at 14:39
  • 2
    A `char *` is not a "C-string"! A pointer is not an array, nor a "string"! And you should get a compiler error for the initialiser. – too honest for this site Jun 27 '16 at 14:40
  • 1
    what do you think `a+7` means when `a` is a string? – 463035818_is_not_an_ai Jun 27 '16 at 14:41
  • 2
    Please grab a copy from one of [these](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – WhiZTiM Jun 27 '16 at 14:41
  • Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) – Lundin Jun 27 '16 at 14:59

1 Answers1

3
char*a = "testing";
sort(a, a+7);

This fails because c-string literals are stored in memory that cannot be edited. It invokes undefined behavior, and in most environments, the operations will simply fail.

string a ="testing";
sort(a , a+7);

This is an ill-formed program. std::string is a proper C++ object, and as a result, a is not a pointer like it is for char* or char[]. std::sort is overloaded to either take pointers or iterators, and if you provide something which is neither, it will not work. That code shouldn't have even compiled, so if it did, you need to update your compiler.

Xirema
  • 19,889
  • 4
  • 32
  • 68
  • There's no overload involved in `std::sort` - it's just a template function accepting any type satisfying the appropriate iterator concepts, which a `char*` does satisfy. – Daniel Schepler Jun 27 '16 at 18:44