1

I am trying to seperate strings that are filled with ' ' and store that in array. For that I wrote code,

string* componentsOfStringSeperatedBystring(string originalString, string stringCompare){

string *arryOfStrings=NULL;

string *tempArrayString = NULL;
for (int i=0; i<originalString.length(); i++) {


    size_t position = originalString.find(stringCompare);
    cout << "\nposition" <<position;

    if (position == originalString.npos) {

        break;
    }
    size_t subStringLength = originalString.length() - position;

    cout << "\nsubStringLength" <<subStringLength;
    string subString = originalString.substr(0,position);

    cout << "\nsubString" <<subString;

    tempArrayString = (string*)realloc(arryOfStrings, (i+1)*sizeof(string));

    cout << "\n i \t" <<i;
    if (tempArrayString != NULL) {

        arryOfStrings = tempArrayString;
        arryOfStrings[i] = subString;
    }


    cout << "\narryOfStrings" <<arryOfStrings;
    originalString = originalString.substr(position+1,subStringLength);
}

return arryOfStrings;
}

I am getting crashed on line "arryOfStrings[i] = subString;", If I simply allocate enough space first, and then without reallocating, I am not getting crashed.

3
  • 1
    The first thing to do is to use std::vector instead of that pointer array you have going on there. Commented Dec 25, 2012 at 11:01
  • +1 @chris why would some one use pointers to string and realloc… Commented Dec 25, 2012 at 11:02
  • @rakeshNS how do you mean seperate strings that are filled with ' ' ? Do you mean separate string by ' ' ? Commented Dec 25, 2012 at 11:08

2 Answers 2

1

Don't use C-style memory management on C++-style objects. Either go fully C-style (use null-terminated char* strings) or go fully C++-style (use std::vector<std::string>).

Sign up to request clarification or add additional context in comments.

1 Comment

I used std::vector<std::string>, and now it is working. Thanks :)
1

You need to use new with std::string not c memory allocation functions.
They do not call constructors for std::string class unlike new. And the constructor for std::string class needs to be called for its proper initialization.

To be honest you shouldn't be using std::string * at all. In doing so You lose all the advantages that were gained in avoiding using char * to begin with. Simply use:

std::vector<std::string>

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.