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));

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.