0
charPointer getCopy(const charPointer& s) //typedef char* charpointer
{
/*
returns a new cstring that is a copy of the cstring s.
That is a new cstring with as big memory as the size of
the cstring s is created and then all the characters of
s including the null char are copied to it.
*/
int len=cstrlen(s);
char *A=new char[len];
for(int i=0;i<len;i++)
{
    A[i]=s[i];
}
A[len]='\0';
return A;
}
  1. How do I return the same string? I'm new to c++ please help!!
  2. ALso if I run in visual c++ it gives me heap destruction error.
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 2
    Your array needs to be `len+1` elements to leave space for the null terminator. Other than that could you explain more clearly what your question is? – Alan Birtles Apr 03 '20 at 06:08
  • 1
    Does this answer your question? [How do I iterate over the words of a string?](https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string) – AAB Apr 03 '20 at 06:18
  • O.T.: Why `typedef char* charpointer`? (It even doesn't save keystrokes.) Why to pass a raw pointer as const reference? Especially, concerning raw pointers (and all the dangers which come with them), I wouldn't hide them in `typedef`s even if they are clearly human-readable. – Scheff's Cat Apr 03 '20 at 06:19
  • 2
    Not to mention that C++ provides something nicer than `char*` -> `std::string`... ;-) – Scheff's Cat Apr 03 '20 at 06:21
  • This solution could be dangerous if no one takes care of the memory allocated in the function. But that depends on what you are trying to do. In general it is best to use the library provided solutions, such as std::string. – mcabreb Apr 03 '20 at 06:47

0 Answers0