Thread: string reversal

  1. #1
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305

    Question string reversal

    Hi,

    I have a doubt about string reversal. The code below reverses the string character by character but when i give it to print out the result there occurs an error. I am unable to figure out where am i going wrong.

    insert
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    void xstrrev(char *);
    
    int main(){
    
    	int i;
    	char *s[] = {
    		"To err is human...",
    		"But to really mess things up...",
    		"One needs to know C!!"
    	};
    
    	for(i=0;i<3;i++){
    		xstrrev(s[i]);
    	}
    }
    
    
    void xstrrev(char *a){
    
    
    	int len,j;
    	char *p;
    
    	printf("\n\r%s", a);
    	len = strlen(a);
    	printf("\n\r%d", len);
    	p = malloc(len+1);
    
    	for(j = 0;j<=len;j++){	
    		p[j] = a[len-j];
    		printf("\n\r%c%c", a[len-j], p[j]);
    		if(j == len)
    			printf("\n\r%s", p);
    	} 
    }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    When j == len in the last iteration of the loop, you will be accessing a out of bounds.

    This is because strlen counts from one when computing the length but array access starts from zero. Normally to iterate over an array you would write something like

    for ( i = 0; i < N; i++ ) ...

    Keep statement blocks like if ( j == len ) outside of the loop. 1. it will confuse you and 2. an if should not be necessary here, as the conditions under which your loop exists are obvious.
    Last edited by whiteflags; 07-03-2009 at 09:46 PM. Reason: wrong variable

  3. #3
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    I was also trying the same problem but with a different approach, but the result is a run time error. Here is my code:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    void xstrrev(char *a)
    {
    	char t;
    	int x,i;
    	x=strlen(a);
    	for(i=0;i!=(x/2);i++)
    	{
    		x--;
    		t=a[i];
    		a[i]=a[x];
    		a[x]=t;
    	}
    	printf("%s\n",a);
    }
    int main()
    {
    
    	int i;
    	char *s[] = {
    		"To err is human",
    		"But to really mess things up",
    		"One needs to know C!!"
    	};
    
    	for(i=0;i<3;i++)
    		xstrrev(s[i]);
    }
    My IDE shows error in the colored line. I'm completely unaware of what's the problem in that line.
    And yes as the problem was similar so I didn't find it necessary to create a new thread for it. Hope its fine.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    One can't change a string literal. "One needs to know C!!" is constant; any attempt to change it will (usually/often) result in a runtime error.

  5. #5
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    That means I can't do this problem by swapping the characters. Or is there a way to do it?
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I wouldn't use that type of logic. An easy adaption might be:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    void xstrrev(char *a)
    {
    	char t;
    	int i, j;
    	j=strlen(a) - 1;
    	for(i=0; i < j; j--,i++)
    	{
                    t=a[i];
            	a[i]=a[j];
                    a[j]=t;
          
    	}
    	printf("%s\n",a);
    }
    int main()
    {
    
    	int i;
    	char *s[] = {
    		"To err is human",
    		"But to really mess things up",
    		"One needs to know C!!"
    	};
    
    	for(i=0;i<3;i++)
    		xstrrev(s[i]);
    
       printf("\n\n\t\t\t    Press Enter When Ready ");
       i = getchar();
       return 0;
    
    }
    Last edited by Adak; 07-04-2009 at 01:50 AM.

  7. #7
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    But that's the main problem even the code you gave is not running.
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  8. #8
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Quote Originally Posted by tabstop View Post
    One can't change a string literal. "One needs to know C!!" is constant; any attempt to change it will (usually/often) result in a runtime error.
    So how is this code working without any problem.
    Code:
    #include <stdio.h>
    int main()
    {
    
    	int i;
    	char *s[] = {
    		"To err is human",
    		"But to really mess things up",
    		"One needs to know C!!"
    	};
    char *a="BEN10";
    	s[2]=a;
    	printf("%s",s[2]);
    }
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  9. #9
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    insert
    Code:
    Quote:
    #include <stdio.h>
    int main()
    {
    
    	int i;
    	char *s[] = {
    		"To err is human",
    		"But to really mess things up",
    		"One needs to know C!!"
    	};
    char *a="BEN10";
    	s[2]=a;
    	printf("%s",s[2]);
    }

    A string literal cannot be changed is true. What you are trying to do above is that you are telling the compiler to give the address of string "BEN10" to char pointer a and then you are assigning that address to s[2] (array of pointers to strings). You are not at all touching or modifying the characters stored at that location. So you dont get any error !!!!!

    But i am still unable to do the string reversal. I have no idea whatsoever of where i am going wrong in the first code that i posted above ????????????????

  10. #10
    DESTINY BEN10's Avatar
    Join Date
    Jul 2008
    Location
    in front of my computer
    Posts
    804
    Quote Originally Posted by roaan View Post
    insert
    Code:
    Quote:
    #include <stdio.h>
    int main()
    {
    
    	int i;
    	char *s[] = {
    		"To err is human",
    		"But to really mess things up",
    		"One needs to know C!!"
    	};
    char *a="BEN10";
    	s[2]=a;
    	printf("%s",s[2]);
    }

    A string literal cannot be changed is true. What you are trying to do above is that you are telling the compiler to give the address of string "BEN10" to char pointer a and then you are assigning that address to s[2] (array of pointers to strings). You are not at all touching or modifying the characters stored at that location. So you dont get any error !!!!!

    But i am still unable to do the string reversal. I have no idea whatsoever of where i am going wrong in the first code that i posted above ????????????????
    This code below works fine, why? Here I'm changing the string literals.
    Code:
    #include<stdio.h>
    #include<string.h>
    int main(void)
    {
    	char s[20]="my name is ben10",t;
    	//gets(s);
    	int i;
    	int len=strlen(s);
    	int x=len/2;
    	for(i=0;i!=x;i++)
    	{
    		len--;
    		t=s[i];
    		s[i]=s[len];
    		s[len]=t;
    	}
    	puts(s);
    return 0;
    }
    HOPE YOU UNDERSTAND.......

    By associating with wise people you will become wise yourself
    It's fine to celebrate success but it is more important to heed the lessons of failure
    We've got to put a lot of money into changing behavior


    PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
    IDE- Microsoft Visual Studio 2008 Express Edition

  11. #11
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by tabstop View Post
    One can't change a string literal. "One needs to know C!!" is constant; any attempt to change it will (usually/often) result in a runtime error.
    Oh wow I didn't see that yesterday.

    Quote Originally Posted by BEN10 View Post
    This code below works fine, why? Here I'm changing the string literals.
    Code:
    #include<stdio.h>
    #include<string.h>
    int main(void)
    {
    	char s[20]="my name is ben10",t;
    	//gets(s);
    	int i;
    	int len=strlen(s);
    	int x=len/2;
    	for(i=0;i!=x;i++)
    	{
    		len--;
    		t=s[i];
    		s[i]=s[len];
    		s[len]=t;
    	}
    	puts(s);
    return 0;
    }
    But you're not changing string literals.

    Earlier you had written char * s[], which declared s an array of char pointers, each element storing the address of a string literal. So when you passed s[i] to xstrrev, you were passing the literal.

    Now you've changed the code to char s[20], which is a typical string. but if you initialize s to something like "foobar" it's the same as this:
    Code:
    char s[20] = { 'f','o','o','b','a','r', '\0' }; /* not a string literal */
    I'm sorry for my earlier oversight.

    Hopefully you can extrapolate from this that you could use a matrix of char to get what you first posted, an array of strings, in a safe way.

    gets is also problematic.
    Last edited by whiteflags; 07-04-2009 at 07:39 AM.

  12. #12
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305
    insert
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    void xstrrev(char *);
    
    int main(){
    
    	int i;
    	static char *s[] = {
    		"To err is human...",
    		"But to really mess things up...",
    		"One needs to know C!!"
    	};
    
    	for(i=0;i<3;i++){
    		xstrrev(s[i]);
    		printf("\n\r%s", s[i]);
    	}
    }
    
    
    void xstrrev(char *a){
    
    	int len,j;
    	char *p, temp;
    
    	//printf("\n\r%c", *a);
    	len = strlen(a);
    	//printf("\n\r%d %d", len, len/2);
    	p = a + len -1;
    	//printf("\n\r%d", p);
    	for(j = 1;j<= len/2;j++){
    	
    		temp = *a;
    		printf("%c %c", temp , *p);
    		*a = *p;
            *p = temp;
    		a++;
    		p--;
    	}
    }

    I tried usign this approach of pointers but still no success when i try to run it gives me an unhandled exception (i thought only java had exceptions)

  13. #13
    Registered User
    Join Date
    Jul 2009
    Posts
    40
    You need return 0 in your main function.

    edit: your header file as well #include <string.h> for you to use strlen() function

  14. #14
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by roaan View Post
    I tried usign this approach of pointers but still no success when i try to run it gives me an unhandled exception (i thought only java had exceptions)
    If you insist on using pointers then you will have to allocate some space with malloc for each element, and then store a copy of the string you want to reverse. As has been explained several times, you cannot edit a string literal. The context in which a string literal is used makes all the difference (see my previous post).

    If you wish to avoid using malloc, the simplest fix for your code is to use a matrix of char instead.

    Code:
    char s[3][512] = {
        "To err is human...",
        "But to really mess things up...",
        "One needs to know C!!"
    };
    Now s[i] should be a writable string instead of a pointer to a string literal.

  15. #15
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by BEN10 View Post
    But that's the main problem even the code you gave is not running.
    Perhaps it doesn't run on your compiler, but it runs just fine on mine (Turbo C).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  2. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM