0

Hello,

Could you explain me why the first approach in the code above works and the second one fails?

#include <cstring>
#include <algorithm>

//char a[] = {'a', 'c', 'b', 'a', 'c', 'b', '\0'}; // Works
char* a = "acbacb"; // Fails

sort(a, a+strlen(a));
2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by vijayan121
0

all literals (including literal strings) are immutable. they are const.
and therefore cannot be sorted (or modified in any way)

//char* a = "acbacb"; // bad programming practice
const char* a = "acbacb"; // the correct way
char b[] = "acbacb"; // also ok. a literal can be used to initialize
                    // an array of modifiable chars
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.