Click here to Skip to main content
12,354,533 members (64,742 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C++ C
I have written a code to reverse the string . It is not working . Is my logic right? How to make it work . I wish to make this one work . I have written using some other logic and it is working . I wish to know how to fix this logic.


#include "stdafx.h"
 

int _tmain(int argc, _TCHAR* argv[])
{
    char *a="This is Anfield"; //Char string
    char *b;  // Reverse string to be copied here
    int count=0; // Count the length of string
    while(*a!='\0')
    {
        count++;
        a++;
    }
    int len=count+1; // Length of string
    int i,j;
    i=j=0;
    for(i=count;i>=0;i--)
    {
        *(a+count)=*(b+j); //Tail of string will be copied to beginning
        j++;
    }
    printf("\n%s",*b);// Print Reversed String
    return 0;
}


There is some run time error in "char *b" Line..
Posted 23-Nov-12 19:15pm
Edited 15-Aug-14 1:44am
Kim Togo26.9K
v2
Comments
Richard MacCutchan 24-Nov-12 4:41am
   
You can use the strlen() function to find the length of the string. Apart from that, read Jochen's suggestions.
Philippe Mori 16-Aug-14 9:33am
   
You can use a debugger and trace the code line per line. If would then be easy to figure that a point to the end of the string after the first loop so adding count to it point outside of the allocated space (and item immediatly after) and thus is illegal.

Then b is not initialized so string would be written to random memory location which is really bad. The behavior of that is undefined. Here it is very easy to figure out half of the problem since the problem occurs at first use. Inspecting b with a debugger and you immediatly knows that it point to garbage.

By the way, that kind of code is good to learn how pointers works but in practice, you should use string class or at least standard C string functions.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 4

This must be a homework assignment because in real life you wouldn't do it this way. You would use the locale aware type, like TCHAR and the function _tcsrev. In a multi-byte project this is equivalent to _strrev and in a Unicode project it becomes _wcsrev.

This or other solutions are not safe from buffer overrun attacks. Better to use a std::string/wstring or std::vector as the container for the string data.

ex:
TCHAR p[] = _T("This is a string");
_tcsrev(p);
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

If pointers you want, then pointers you'll have:
(the following C code reverses the string in-place)
#include <stdio.h>
int main()
{
  char s[] = "This is Anfield";
  char * p, *q;
 
  p = q = s;
  while (*++q);
  while (*q) q++; // more robust, see Member 9586495 comment.
  q--;
  while (q>p)
  {
    char c = *p;
    *p++ = *q;
    *q-- = c;
 
  }
  printf("%s\n", s);
  return 0;
}
  Permalink  
v4
Comments
Nelek 24-Nov-12 5:59am
   
That's evil :laugh: +5
CPallini 24-Nov-12 6:14am
   
It is not my fault, he asked for pointers!
:-)
nv3 24-Nov-12 6:26am
   
You could have copied the original string to a buffer and then reverse it in place. ;-)
CPallini 24-Nov-12 7:00am
   
Yes. If he doesn't want to modify the original string then a preventive call to strdup is enough.
Member 9586495 26-Nov-12 3:58am
   
Solution 3 works not correct with char s[] = "";
My proposal is to replace the line "while (*++q);" by "while (*q)q++;"
Best regards
CPallini 26-Nov-12 4:18am
   
How did you test it (it works on my system)?

Member 9586495 26-Nov-12 5:17am
   
Hi,
I changed only the code line to 'char s[] = "";' and I got
nonsens as print output on my windows 7 system.
CPallini 26-Nov-12 5:29am
   
OK, now I got it, you are right, I've updated my solution. Thank you.
Philippe Mori 16-Aug-14 9:22am
   
See my other comment. Although updated code would works, q would point before s if the string was empty thus either decrementing should be moved or you should check for empty string first.
missak boyajian 26-Nov-12 9:27am
   
Hey. Can someone please explain this:
//while (*++q);
while (*q) q++;
q--;
Philippe Mori 16-Aug-14 9:19am
   
I think that q--; should be done Inside loop only. Thus second line in loop block should be *p++ - *--q; and third line should be *q = c;.

Otherwise, you make q point before the array. I would think that it is undefined behavior by the standard but it would always works in practice as an address of 0 would never be allocated by C language.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Your code contains multiple errors:
  • You are copying data to unalloacted memory (*b)
  • The variable b is not initialized
  • The trailing NULL char for b is not set
  • The variable len is never used
  • You are passing the wrong parameter (*b) to printf
You must allocate memory for the destination string, add a NULL byte after coyping the reversed data to it, and finally free the memory:
b = new char[len];
// Reverse code here
b[count] = 0;
printf("\n%s", b);
delete [] b;
  Permalink  
Comments
Philippe Mori 16-Aug-14 9:38am
   
And *(a + count) in the loop make no sense as a already point to the end (thus adding count will point twice too far) and that expression is constant for the whole loop (thus always updating the same character).
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Hi Steven,

Please update your code as below

int _tmain(int argc, _TCHAR* argv[])
{
    char *a="This is Anfield"; //Char string
    char *b;  // Reverse string to be copied here
    int count=0; // Count the length of string
    while(*a!='\0')
    {
        count++;
        a++;
    }
    int len=count+1; // Length of string
    int i,j;
    i=j=0;
    for(i=count;i>=0;i--)
    {
        *(b+j) = *(a+i); //Tail of string will be copied to beginning
        j++;
    }
    printf("\n%s",*b);// Print Reversed String
    return 0;
}

Hope this will help you.
  Permalink  
v2
Comments
steven8Gerrard 24-Nov-12 3:03am
   
STill getting error . Uninitialised Local variable used
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 5

int _tmain(int argc, _TCHAR* argv[])
{
    char *a="This is c Language"; //Char string
    char *b;  // Reverse string to be copied here
    int count=0; // Count the length of string
    while(*a!='\0')
    {
        count++;
        a++;
    }
    int i;
    b =(char*) malloc(count);//Allocate memory for reverse string
    for(i=0;i<count;i++)>
    {
        *(b+i) = *(a-i-1); //Tail of string will be copied to beginning
    }
    *(b+i)='\0';//Add termination of string
    printf("\n%s" ,b);// Print Reversed String
    free(b);
 
    return 0;
}
  Permalink  
v3
Comments
Richard MacCutchan 16-Aug-14 6:48am
   
Please don't waste time posting answers to old questions. It is most unlikely that the questioner still has any interest in the problem.
Member 11014617 5-Oct-14 12:46pm
   
I am new to this community . I will care from next times.
Philippe Mori 16-Aug-14 9:45am
   
You have forgotten to free allocated memory...
Member 11014617 5-Oct-14 12:47pm
   
Corrected ..
CPallini 5-Oct-14 16:03pm
   
1) You don't check malloc return value.
2) In
*(b+i)='\0';//Add termination of string
You are assigning b[count]. That is buffer overflow.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160621.1 | Last Updated 5 Oct 2014
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100