Re: Reversing a String
Alamelu wrote:
I am trying to reverse a string
void ReverseString(const char * pinput, char **pOutput)
{
char *ptempinput = new char[strlen(pinput)];
strcpy(ptempinput, pinput);
Note: before dereferencing pointers, you should at least assert() that they
are not null. Passing null to strlen() invokes undefined behaviour.
Further, how often do you want to compute the length of the input? I count
three times, once the result is stored in a variable that is then not used
in subsequent cases where it is used. Lastly, but see my final comment
below, too, you need 'n+1' chars to store a string with length n. Reread
the string-handling section in your book.
int length = static_cast<int>(strlen(pinput));
Argh! Use size_t instead of performing a static cast that truncates the size
and changes the signedness of the result! In general, don't cast at all,
rather use the correct type all along so you don't have to do any
conversions.
char *pOut = new char[strlen(pinput)];
Hmmm, what if this 'new' throws an exception (std::bad_alloc)? In that case,
the content of ptempinput is leaked. In fact you're not doing any cleanup
whatsoever, did you skip that chapter?
char get = *(ptempinput + 3);
The term '*(x+n)' is equivalent to 'x[n]' while the latter is much more
readable IMHO...
char get2 = ptempinput[4];
....like this.
for(int k = 0; length >= 0 ;k++)
{
pOut[k] = ptempinput[length--]; //Here pOut[k] takes appropriate
value, but pOut doesn't hold the reveresed "Hello"
}
[...]
Where am i going wrong?
Change the body of the loop to this:
size_t target = k;
size_t source = length--;
std::cout << "Copying from " << source << " to " << target << std::endl;
pOut[target] = ptempinput[source];
....and you will get some insight into what is happening.
Suggest me a link, from where i can learn about handling char* ?
Don't, use std::string instead.
Uli