C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 07-03-2009, 09:29 PM   #1
Registered User
 
Join Date: Jun 2009
Location: US of A
Posts: 300
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);
	} 
}
roaan is offline   Reply With Quote
Old 07-03-2009, 09:42 PM   #2
Registered User
 
Join Date: Apr 2006
Location: United States
Posts: 3,201
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.
__________________
Os iusti meditabitur sapientiam
Et lingua eius loquetur indicium

"There is nothing either good or bad, but thinking makes it so." (Shakespeare, Hamlet, Act II scene ii)

http://www.myspace.com/whiteflags99

Last edited by whiteflags; 07-03-2009 at 09:46 PM. Reason: wrong variable
whiteflags is offline   Reply With Quote
Old 07-04-2009, 12:27 AM   #3
DESTINY
 
BEN10's Avatar
 
Join Date: Jul 2008
Location: in front of my computer
Posts: 656
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.......

for( ; ; )
printf("If you can't make it good, at least make it look good");

PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
IDE- Microsoft Visual Studio 2008 Express Edition
BEN10 is offline   Reply With Quote
Old 07-04-2009, 01:13 AM   #4
and the Hat of Guessing
 
tabstop's Avatar
 
Join Date: Nov 2007
Posts: 8,740
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.
tabstop is offline   Reply With Quote
Old 07-04-2009, 01:45 AM   #5
DESTINY
 
BEN10's Avatar
 
Join Date: Jul 2008
Location: in front of my computer
Posts: 656
That means I can't do this problem by swapping the characters. Or is there a way to do it?
__________________
HOPE YOU UNDERSTAND.......

for( ; ; )
printf("If you can't make it good, at least make it look good");

PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
IDE- Microsoft Visual Studio 2008 Express Edition
BEN10 is offline   Reply With Quote
Old 07-04-2009, 01:46 AM   #6
Registered User
 
Join Date: Sep 2006
Posts: 2,501
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.
Adak is offline   Reply With Quote
Old 07-04-2009, 01:51 AM   #7
DESTINY
 
BEN10's Avatar
 
Join Date: Jul 2008
Location: in front of my computer
Posts: 656
But that's the main problem even the code you gave is not running.
__________________
HOPE YOU UNDERSTAND.......

for( ; ; )
printf("If you can't make it good, at least make it look good");

PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
IDE- Microsoft Visual Studio 2008 Express Edition
BEN10 is offline   Reply With Quote
Old 07-04-2009, 01:54 AM   #8
DESTINY
 
BEN10's Avatar
 
Join Date: Jul 2008
Location: in front of my computer
Posts: 656
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.......

for( ; ; )
printf("If you can't make it good, at least make it look good");

PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
IDE- Microsoft Visual Studio 2008 Express Edition
BEN10 is offline   Reply With Quote
Old 07-04-2009, 06:52 AM   #9
Registered User
 
Join Date: Jun 2009
Location: US of A
Posts: 300
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 ????????????????
roaan is offline   Reply With Quote
Old 07-04-2009, 06:58 AM   #10
DESTINY
 
BEN10's Avatar
 
Join Date: Jul 2008
Location: in front of my computer
Posts: 656
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.......

for( ; ; )
printf("If you can't make it good, at least make it look good");

PC specifications- 512MB RAM, Windows XP sp3, 2.79 GHz pentium D.
IDE- Microsoft Visual Studio 2008 Express Edition
BEN10 is offline   Reply With Quote
Old 07-04-2009, 07:18 AM   #11
Registered User
 
Join Date: Apr 2006
Location: United States
Posts: 3,201
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.
__________________
Os iusti meditabitur sapientiam
Et lingua eius loquetur indicium

"There is nothing either good or bad, but thinking makes it so." (Shakespeare, Hamlet, Act II scene ii)

http://www.myspace.com/whiteflags99

Last edited by whiteflags; 07-04-2009 at 07:39 AM.
whiteflags is offline   Reply With Quote
Old 07-04-2009, 08:06 AM   #12
Registered User
 
Join Date: Jun 2009
Location: US of A
Posts: 300
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)
roaan is offline   Reply With Quote
Old 07-04-2009, 08:38 AM   #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
WatchTower is offline   Reply With Quote
Old 07-04-2009, 08:55 AM   #14
Registered User
 
Join Date: Apr 2006
Location: United States
Posts: 3,201
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.
__________________
Os iusti meditabitur sapientiam
Et lingua eius loquetur indicium

"There is nothing either good or bad, but thinking makes it so." (Shakespeare, Hamlet, Act II scene ii)

http://www.myspace.com/whiteflags99
whiteflags is offline   Reply With Quote
Old 07-04-2009, 09:41 AM   #15
Registered User
 
Join Date: Sep 2006
Posts: 2,501
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).
Adak is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

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


All times are GMT -6. The time now is 05:05 PM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.0 RC2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22