473,549 Members | 3,109 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String reversal from K & R 2nd edition

I tried using the string reversal routine that occurs in K & R 2nd
edition (Pg. 62) & the program core dumps.

#include <stdio.h>
#include <stdlib.h>

void reverse ( char s[] )
{
int c, i, j;

printf("\nInput string is %s",s);

for (i=0, j= strlen(s)-1;i<j;i++,j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}

printf("\nRever sed string is %s",s);
}

int main()
{
reverse("abcd") ;
}

Apart from the two prints, this is an exact copy of the routine. I am
using gcc on Cygwin.

Can someone tell me whats going wrong?

Thanks,
Ashok

Nov 14 '05 #1
6 5369
as***********@g mail.com wrote:
I tried using the string reversal routine that occurs in K & R 2nd
edition (Pg. 62) & the program core dumps.

#include <stdio.h>
#include <stdlib.h>

void reverse ( char s[] )
{
int c, i, j;

printf("\nInput string is %s",s);

for (i=0, j= strlen(s)-1;i<j;i++,j--)
{
c = s[i];
s[i] = s[j];
s[j] = c;
}

printf("\nRever sed string is %s",s);
}

int main()
{
reverse("abcd") ;
}

Apart from the two prints, this is an exact copy of the routine. I am
using gcc on Cygwin.

Can someone tell me whats going wrong?

Thanks,
Ashok


You are attempting to modify a string literal, can't do that.

try this:
int main(void)
{
char foo[] = "abcd";
reverse(foo);
return 0;
}

You should put a '\n' at the end of your printfs
rather than the beginning, the last one may
or may not be displayed.

You should check for a 0 length string too, not
if strlen(s) is 0;

-David
Nov 14 '05 #2
Thanks David. Indeed the error was that a string literal was attempted
to be modified.

Here is what I finally got.

#include <stdio.h>
#include <string.h>

void reverse ( char *str )
{
int i; int len = strlen(str);
if (!len) return;
printf("Input string is %s \n", str);
for ( i=0; i < len/2; i++)
{
*(str + len-1-i) ^= *(str+i) ^= *(str + len -1-i) ^=
*(str+i);
}

printf("Output string is %s \n", str);

}

int main ()
{
char mystr[] = "abcde";
reverse(mystr);
}

Is the strlen implemented here same as what you are referring to?

Ashok

Nov 14 '05 #3
In article <11************ **********@z14g 2000cwz.googleg roups.com>
<as***********@ gmail.com> wrote:
Here is what I finally got.
[snippage]
*(str + len-1-i) ^= *(str+i) ^= *(str + len -1-i) ^= *(str+i);


"Don't do that":

Archive-name: C-faq/faq
Comp-lang-c-archive-name: C-FAQ-list
URL: http://www.eskimo.com/~scs/C-faq/top.html

[Last modified July 3, 2004 by scs.]

3.3b: Here's a slick expression:

a ^= b ^= a ^= b

It swaps a and b without using a temporary.

A: Not portably, it doesn't. It attempts to modify the variable a
twice between sequence points, so its behavior is undefined.

For example, it has been reported that when given the code

int a = 123, b = 7654;
a ^= b ^= a ^= b;

the SCO Optimizing C compiler (icc) sets b to 123 and a to 0.

See also questions 3.1, 3.8, 10.3, and 20.15c.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #4
as***********@g mail.com wrote:
void reverse ( char *str )
{
int i; int len = strlen(str);
if (!len) return;
printf("Input string is %s \n", str);
for ( i=0; i < len/2; i++)
{
*(str + len-1-i) ^= *(str+i) ^= *(str + len -1-i) ^=
*(str+i);
}

printf("Output string is %s \n", str);

}


A simpler pointer solution. It appeared that you wanted something
optimized, and pointers can be better than indexes. But maybe
compilers are smarter now.

void reverse ( char *s )
{
char c ;
char *s1, *s2 ;

printf("Input string is %s\n",s);

for ( s1=s, s2=s+strlen(s)-1 ; s1 < s2 ; s1++, s2-- )
{
c = *s1 ;
*s1 = *s2 ;
*s2 = c ;
}
printf("Reverse d string is %s\n",s);
}

David Stevenson
Nov 14 '05 #5
David Stevenson wrote:
void reverse ( char *s )
{ char *s1, *s2 ; s2=s+strlen(s)-1 ;


That's no good for when s points to a zero length string.

--
pete
Nov 14 '05 #6
David Stevenson wrote:
void reverse ( char *s )
{
[...]
for ( s1=s, s2=s+strlen(s)-1 ; s1 < s2 ; s1++, s2-- )


As pete already pointed out:
s2=s+strlem(s)-1; is bad when strlen(s) == 0.

So here is a way to fix this (based on David Stevenson's code):

#include <assert.h>
#include <string.h>
#include <stdio.h>

char* reverse ( char *s )
{
char c ;
char *s1, *s2 ;

assert(s != NULL);

if (*s == '\0')
return s;

for ( s1=s, s2=s+strlen(s)-1 ; s1 < s2 ; s1++, s2-- )
{
c = *s1 ;
*s1 = *s2 ;
*s2 = c ;
}

return s;
}

int main(void)
{
char s[]="abc";

printf("Origina l string: %s\n",s);
printf("Reverse d string: %s\n",reverse(s ));

return 0;
}

Note:
I've added a return type (char*) to reverse(), and added the assertion
that s shouldn't be NULL, as both of this additions didn't seem like a
bad idea for me.

--
Robert Bachmann <ne**@rbach.pri v.at>, PGP-KeyID: 0x8994A748
Nov 14 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

74
5002
by: Michael | last post by:
As if we needed another string reversal question. I have a problem with the following code, that I believe should work. int StringReverse(char* psz) { char *p = psz; char *q = psz + strlen(psz) - 1; while (p < q) {
45
5277
by: Rakesh | last post by:
Hi, I have this function to reverse the given string. I am just curious if that is correct and there could be better way of doing it / probable bugs in the same. The function prototype is similar to the one in any standard C library. <---- Code starts -->
24
3234
by: Sathyaish | last post by:
This one question is asked modally in most Microsoft interviews. I started to contemplate various implementations for it. This was what I got. #include <stdio.h> #include <stdlib.h> #include <string.h> char* StrReverse(char*);
12
1704
by: Sathyaish | last post by:
How would you reverse a string "in place" in python? I am seeing that there are a lot of operations around higher level data structures and less emphasis on primitive data. I am a little lost and can't find my way through seeing a rev() or a reverse() or a strRev() function around a string object. I could traverse from end-to-beginning by...
25
2725
by: Frederick Gotham | last post by:
I was intrigued by someone the other day who posted regarding methods of "mirror-imaging" the bits in a byte. I thought it might be interesting to write a fully-portable algorithm for mirror-imaging (i.e. reversing) an entire chunk of memory, and making the algorithm as fast as possible (yes, I realise it may be faster on some machines than on...
41
3339
by: rick | last post by:
Why can't Python have a reverse() function/method like Ruby? Python: x = 'a_string' # Reverse the string print x Ruby: x = 'a_string' # Reverse the string
3
6090
by: steezli | last post by:
Hi, Brand new to VB.NET and I'm having a problem figuring out this program. I'll try and be descritive as possible. I have to create a Windows application that contains a single top-level form with two textboxes on it, on positioned above the other. As each character is entered into the upper textbox, the string that has been entered...
38
2686
by: ssecorp | last post by:
char* reverse(char* str) { int length = strlen(str); char* acc; int i; for (i=0; i<=length-1; i++){ acc = str; } return acc; }
144
4882
by: dominantubergeek | last post by:
Hello, I'm a highly experienced expert C programmer and I've written this code to reverse a string in place. I think you could all learn something from it! int reverse(char* reverseme){ int retval=-1; if(retval!=NULL){ int len=strlen(retval){ if(len>0){ int half=len>>1;
0
7520
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7446
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7718
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7470
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7809
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5368
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5088
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1936
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
763
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.