user3558697
user3558697

Reputation: 17

Invalid conversion from char to String* C++

String* substr(String* str, int start, int end)
{   
   String* substring = new String;
   for(int i = start; i < end; i++)
   {
       substring =  str->text[i];
   }   

   return substring;
}

I need to store the substring located in the text array member of my String struct. The method is supposed to take part of the array(separated by delimiters) and store it in variables str1 and str2 then compare them. I am having problems with the 6th line where the string is being substring is supposed to be created and stored.

Upvotes: 0

Views: 337

Answers (1)

001
001

Reputation: 13533

Since no one else has answered... First change your struct:

struct String {
    char* text;    // Removed const
    int sz;
};

Now, change your function

String* substr(String* str, int start, int end)
{   
   String* substring = new String;

   //Alloc enough space to hold chars + EOS
   substring->text = new char[end - start + 1]; 
   // Save string length - does not include EOS
   substring->sz = end - start;       

   for(int i = start; i < end; i++)
   {
       // TODO: Error checking should be added to make sure it doesn't go
       // beyond original string bounds

       // Copy the substring
       substring->text[i - start] =  str->text[i];
   }
   // Add end of string
   substring->text[substring->sz] = '\0';

   return substring;
}

Note, doing it this way, you later need to delete both the array and the struct:

delete [] substring->text;
delete substring;

Or, you can just use std::string...

Upvotes: 1

Related Questions