2

I want to sort each string of array of strings , here is my code that i tried.

#include <iostream>
#include <algorithm>

void _sort_word(char *str)
{
    int len = strlen(str); 
    std::sort(str,str+len); // program get stuck here. 
}
int main()
{
    char *str[] = {"hello", "world"};
    for(int i=0;i<2;i++){
        _sort_word(str[i]);
        cout << str[i] << "\n";
    }
}

I want to know is sort(str,str+len); a valid statement here, if not what should be done instead ?

8
  • 4
    The problem is that std::sort() needs write access the underlying memory, which currently is a char string literal and you can't change anything there. Commented Jun 22, 2016 at 13:43
  • Can i somehow convert string literal to character array and send it to _sort_word() function ? Commented Jun 22, 2016 at 13:47
  • 1
    You need a better compiler or need to turn up your warnings: coliru.stacked-crooked.com/a/397b8016997e5c95 Commented Jun 22, 2016 at 13:47
  • 1
    @saurabhagarwal Try char str[2][6] = {"hello", "world"}; if the max length is 6. Commented Jun 22, 2016 at 13:49
  • 1
    Also see something about starting an identifier with an underscore Commented Jun 22, 2016 at 13:50

1 Answer 1

6

First of all string literals in C++ have types of constant character arrays. So the correct array declaration will look like

const char *str[] = {"hello", "world"};
^^^^^

Thus the string literals pointed to by the elements of the array are immutable.

You should declare at least a two dimensional array.

Here is a demonstrative program

#include <iostream>
#include <algorithm>
#include <cstring>

void sort_word( char *s )
{
    size_t l = std::strlen( s ); 
    std::sort( s, s + l ); 
}


int main() 
{
    char str[][6] = { "hello", "world" };

    for ( auto &s : str ) sort_word( s );
    for ( auto &s : str ) std::cout << s << std::endl;

    return 0;
}

Its output is

ehllo
dlorw

If your compiler does not support the range based for statement then you can write instead

for ( size_t i = 0; i < sizeof( str ) / sizeof( *str ); i++ ) sort_word( str[i] );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.