Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
int GetLength(const char* string)
{
  int iLength;
  for(iLength = 0; (*(string + iLength) != '\0'); iLength++)
    ;
  return iLength;
}
void Reverse(char* string)
{
  int iLength = GetLength(string);
  char* pTemp = new char[iLength+1];
  memcpy(pTemp, string, iLength+1);
  for(int i = 0; i < iLength; i++)
  {
    *(string+i) = *(pTemp + iLength - i -1);//Access violation in first iteration
  }
  *(pTemp+iLength) = '\0';
  delete []pTemp;
  pTemp == NULL;
}
Posted
Comments
Mohibur Rashid 4-Dec-14 0:41am    
You have sent constant string as data to Reverse function, I suppose. You can't do that. It will definitely generate error. Besides your logic is not good enough to reverse an string.
Shubha Debnath 4-Dec-14 1:13am    
Yes I understand and the problem get resolved. Previously I was sending a constant sting; that is why it does not allow me to assign value. Now I have allocated the string before calling the function and it worked.

Thanks Mohibur. Please give me a better idea of reversing a string.

C++
string t = string ( t.rbegin(), t.rend() );


string ( ) is the string constructor which creates a new string object ( String definition[^] )

rbegin and rend are reverse iterators, an iterator is an object which acts in a similar way to a pointer ( Reverse iterator link[^]
rbegin link[^] )


string ( tekst.rbegin(), tekst.rend() ) creates a string from the beginning to the of the reversed 't'

If this helps please take time to accept the solution. Thank you.
 
Share this answer
 
v2
The code you posted works, provided the string you pass to Reverse() is really a 0-terminated string! You should at the very least test string against nullptr, because that's pretty much the only thing that could cause an access violation:
C++
void Reverse (char* string) {
   if (string == nullptr)
      return;
   ...
}


If that's not it (or even if it is!), learn to use a debugger, break at the point where you get the access violation, and check the current values of your variables.
 
Share this answer
 
As a matter of fact, I should not offer you any solution. But here is the thing you can do, very simple:
C++
for(i=0;i<len;i++) 
{
 swap(str+i, str-i);// you should write the swap function or related code and also figure out how it works 
}


And also try to understand what stephan lang have said
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900