Search code examples
c++cchardynamic-memory-allocationstrcmp

How to declare an empty char* and increase the size dynamically?


Let's say I am trying to do the following (this is a sub problem of what I am trying to achieve):

int compareFirstWord(char* sentence, char* compareWord){
      char* temp; int i=-1;
      while(*(sentence+(++i))!=' ') { *(temp+i) = *(sentence+i); }
      return strcmp(temp, compareWord); }

When I ran compareFirstWord("Hi There", "Hi");, I got error at the copy line. It said I was using temp uninitialized. Then I used char* temp = new char[]; In this case the function returned 1 and not 0. When I debugged, I saw temp starting with some random characters of length 16 and strcmp fails because of this.

Is there a way to declare an empty char* and increase the size dynamically only to length and contents of what I need ? Any way to make the function work ? I don't want to use std::string.


Solution

  • In C, you may do:

    int compareFirstWord(const char* sentence, const char* compareWord)
    {
        while (*compareWord != '\0' && *sentence == *compareWord) {
            ++sentence;
            ++compareWord;
        }
        if (*compareWord == '\0' && (*sentence == '\0' || *sentence == ' ')) {
            return 0;
        }
        return *sentence < *compareWord ? -1 : 1;
    }
    

    With std::string, you just have:

    int compareFirstWord(const std::string& sentence, const std::string& compareWord)
    {
        return sentence.compare(0, sentence.find(" "), compareWord);
    }