if you have a const char* that means you cannot change the data that the pointer points to.
Line 79 changes the data. That's why you get the error. 'substr' should not be a const pointer.
As for the memory leak, you have 3 options:
1) make the calling function responsible for providing the output buffer
ie:
void strsub(char* out,const char* in,int one,int two)
That way, the function does not need to allocate any memory at all. This is what is done by strcpy and similar standard lib functions.
2) make the calling function responsible for deleting the allocated memory.
ie:
1 2 3
|
char* foo = strsub("stuff",1,3);
cout << foo;
delete[] foo; // since I called strsub, I'm responsible for cleanup
|
3) use strings instead of char arrays.
Obviously #3 is the best. But if you can't use strings for whatever reason #1 would be my next recommendation. I really don't recommend #2 at all, but I mentioned it for completeness.
You also have another big problem here:
1 2 3
|
char* substr = new char[two+2]; // allocates memory, substr points to allocated memory
//substr=(cstr+one); // BAD. this does not copy the string.
strcpy(substr,cstr+one); // you probably meant to do this
|
note that when you do
substr=(cstr+one);
, substr no longer points to the memory you allocated. Instead it points to the same buffer that cstr points to.