Thread: String Revarsal

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    83

    String Revarsal

    Dear All,
    I want reverse string i wrote code as follow:-
    Code:
    #include "stdio.h"
    #include "string.h"
    int main()
    {
      char *str="shwetha";
      char *str1;
      while(*str!='\0')
      str++;
      while(*str1!='\0')
      {
        *str1=*str;
        str1++;
        str++;
      }
    str1='\0';
    printf("%s", str1);
    return 0;
    }
    i am getting Run time error what is the problem?

  2. #2
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    You're overwriting a string literal, which is generally not allowed. Declare your string as follows:

    Code:
    char str[]="shwetha";

  3. #3
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459
    Also perhaps think of more meaningful names.

    As "str!" looks like "str1" at a glance.

  4. #4
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    And unless I missed it, str1 doesn't point to anything meaningful.

  5. #5
    Registered User The Dog's Avatar
    Join Date
    May 2002
    Location
    Cape Town
    Posts
    788
    Be simple. The original string has 7 characters, so make space for str1.

    Also, your logic is completely flawed.

    str must move from the back to the front (decrement the pointer),
    and str1 must move from the front the back (increment the pointer),
    yet in your code, you increment both pointers all the time...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  2. C++ ini file reader problems
    By guitarist809 in forum C++ Programming
    Replies: 7
    Last Post: 09-04-2008, 06:02 AM
  3. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM