0

I've run into a strange, and very specific issue. As some background, I need to support some legacy code that's passing around a lot of large c-style strings. Since these get pretty gigantic, I want to avoid unnecessarily copying that data, which would include copy constructing std::strings just for one operation.

I want to use std::sort on these strings, but they obviously lack iterators. However, according to the documentation for std::sort, I should just be able to pass in two pointers for any contiguous random access memory, but it isn't working with my c-style string

Basically it's like this:

char* foo = "test string";
std::sort(foo, foo + 11);    // access violation occurs

However:

char foo[] = "test string";
std::sort(foo, foo + 11);    // perfect fine, sorted correctly

This is extra confusing to me, because as far as I know, char* and char[] are essentially the same. Why does char* break, while char[] succeeds? How can I pass a c-style string into an STL algorithm?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
kamstack
  • 81
  • 4

1 Answers1

4
char* foo = "test string";

This is a pointer to a string literal, which is stored in read-only memory, thus you cannot modify/sort it.


Your code should be giving you a warning, similar to this:

Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall main.cpp 
main.cpp:3:17: warning: conversion from string literal to 'char *' is deprecated
      [-Wc++11-compat-deprecated-writable-strings]
    char* foo = "test string";
                ^

Please read: What is the difference between char s[] and char *s?

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305