473,804 Members | 3,049 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String reversing problem

Why doesn't:

#include <stdio.h>

void reverse(char[], int);

main()
{
char s[5];

s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';
reverse(s, 5);

for (int i=0; i<=4; i++)
putchar(s[i]);
return 0;
}

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

for (i=0,j=num_elem ents-1; (i<=num_element s-1) && (j>=0); i++,j--)
s[i] = s[j];
}

output:

olleh

?

Dec 30 '05
46 2158
Chuck F. wrote:
pai wrote:

I think an extra variable is needed to store, bcoz u cant
interchange 2 variable as such. or is there any way to do it

Include context, without which your message is meaningless. For
means on the broken google interface, see my sig below.

Try this, after #include <string.h>:

/* reverse string in place. Return length */
static size_t revstring(char *stg)
{
char *last, temp;
size_t lgh;

if ((lgh = strlen(stg)) > 1) {
last = stg + lgh; /* points to '\0' */
while (last-- > stg) {
temp = *stg; *stg++ = *last; *last = temp;
}
}
return lgh;
} /* revstring */

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>


Hi,

I agree on the previous, and, of course, if some day I need to code
something similar I will write more or less the same (specially in an
answer to a beginner).

But, just for fun, and taken into account is the third time this
question has been posted, another version:

int revstring ( char *s )
{
char *e;
int r;
for( e=s+(r=strlen(s ))-1; s<e; *s^=*e^=*s^=*e, s++, e--);
return r;
}
Kind regards.

(hope google doesn't heats indentation).

Dec 30 '05 #11
"Albert" <al************ *****@gmail.com > wrote in message
news:11******** *************@g 43g2000cwa.goog legroups.com...
What do you mean by 'desk checking'?


I'd have called it "paper check," or, when I'm feeling whimsical "let's play
computer."

Whatever way it's expressed, it means get out some paper and a pen(cil) and
perform, yourself, the steps the computer will take to execute your program.
Sometimes it's better (or quicker) than a debugger. Sometimes it's the only
way to debug (for very limited platforms, for example). Well worth practicing.

- Bill
Dec 30 '05 #12
tmp123 wrote:
Chuck F. wrote:
.... snip ...
/* reverse string in place. Return length */
static size_t revstring(char *stg)
{
char *last, temp;
size_t lgh;

if ((lgh = strlen(stg)) > 1) {
last = stg + lgh; /* points to '\0' */
while (last-- > stg) {
temp = *stg; *stg++ = *last; *last = temp;
}
}
return lgh;
} /* revstring */

.... snip ...
But, just for fun, and taken into account is the third time this
question has been posted, another version:

int revstring ( char *s )
{
char *e;
int r;
for( e=s+(r=strlen(s ))-1; s<e; *s^=*e^=*s^=*e, s++, e--);
return r;
}


FYI your version invokes undefined behaviour. Try it with a string
of zero chars. My length test is not there for fun. I also have
evil suspicions about the xor operations.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Dec 30 '05 #13
Chuck F. wrote:
tmp123 wrote:
int revstring ( char *s )
{
char *e;
int r;
for( e=s+(r=strlen(s ))-1; s<e; *s^=*e^=*s^=*e, s++, e--);
return r;
}


FYI your version invokes undefined behaviour. Try it with a string
of zero chars. My length test is not there for fun. I also have
evil suspicions about the xor operations.


Hi,

If length is 0, then e=s-1, thus s<e is false exiting loop.

However, if the usage of pointer comparation and pointer substraction
is not welcome, another version:

void revstring ( char *s )
{
char *e;
for( e=s+strlen(s); s!=e-- && s!=e; *s^=*e^=*s++^=* e);
}

Kind regards.

PS: some days ago, someone posted about if "C is easy". I do not known,
but it is tricky.

Dec 30 '05 #14
"tmp123" <tm****@menta.n et> writes:
[...]
void revstring ( char *s )
{
char *e;
for( e=s+strlen(s); s!=e-- && s!=e; *s^=*e^=*s++^=* e);
}
Undefined behavior.
PS: some days ago, someone posted about if "C is easy". I do not known,
but it is tricky.


It can be if you go out of your way to make it tricky.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 30 '05 #15

Keith Thompson wrote:
"tmp123" <tm****@menta.n et> writes:
[...]
void revstring ( char *s )
{
char *e;
for( e=s+strlen(s); s!=e-- && s!=e; *s^=*e^=*s++^=* e);
}


Undefined behavior.


Could be... but, could you prove your statement?

Dec 30 '05 #16
"tmp123" <tm****@menta.n et> writes:
Keith Thompson wrote:
"tmp123" <tm****@menta.n et> writes:
[...]
void revstring ( char *s )
{
char *e;
for( e=s+strlen(s); s!=e-- && s!=e; *s^=*e^=*s++^=* e);
}


Undefined behavior.


Could be... but, could you prove your statement?


Even the first half of the control expression (namely, 's!=e--')
can yield undefined behavior if strlen(s) == 0.
Dec 30 '05 #17
"tmp123" <tm****@menta.n et> writes:
Keith Thompson wrote:
"tmp123" <tm****@menta.n et> writes:
[...]
> void revstring ( char *s )
> {
> char *e;
> for( e=s+strlen(s); s!=e-- && s!=e; *s^=*e^=*s++^=* e);
> }


Undefined behavior.


Could be... but, could you prove your statement?


The expression
*s^=*e^=*s++^=* e
modifies both *s and *e twice between sequence points.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Dec 30 '05 #18
In article <11************ **********@g47g 2000cwa.googleg roups.com>,
"tmp123" <tm****@menta.n et> wrote:
Keith Thompson wrote:
"tmp123" <tm****@menta.n et> writes:
[...]
void revstring ( char *s )
{
char *e;
for( e=s+strlen(s); s!=e-- && s!=e; *s^=*e^=*s++^=* e);
}


Undefined behavior.


Could be... but, could you prove your statement?


It's kind of obvious. Even if it wasn't, whoever wrote that kind of code
should be slapped silly. Immediate removal from any programming team
that I am involved with.
Dec 30 '05 #19
tmp123 wrote:
Chuck F. wrote:
tmp123 wrote:
> int revstring ( char *s )
> {
> char *e;
> int r;
> for( e=s+(r=strlen(s ))-1; s<e; *s^=*e^=*s^=*e, s++, e--);
> return r;
> }
FYI your version invokes undefined behaviour. Try it with a
string of zero chars. My length test is not there for fun. I
also have evil suspicions about the xor operations.


If length is 0, then e=s-1, thus s<e is false exiting loop.

However, if the usage of pointer comparation and pointer
substraction is not welcome, another version:

void revstring ( char *s )
{
char *e;
for( e=s+strlen(s); s!=e-- && s!=e; *s^=*e^=*s++^=* e);
}


Same problem and undefined behaviour. You are not allowed to
generate a pointer that points before s (although you are allowed
to generate one that points just after s).

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Dec 30 '05 #20

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

Similar topics

45
5326
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
3287
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*);
5
1353
by: Shwetabh | last post by:
Hi, How can I remove a part of string from complete string in SQL? this is something i want to do: update ace set PICTURE = PICTURE - '\\SHWETABH\Shwetabh\I\' But here ' - ' is not allowed.
41
3394
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
4
2416
by: Jonathan Wood | last post by:
Is it just me? It seems like one moving from MFC to C# loses some string functionality such as the two mentioned in the subject. Did I miss something? -- Jonathan Wood SoftCircuits Programming http://www.softcircuits.com
2
12071
by: Kelly B | last post by:
I tried to write a code which would reverse the order of words in a given string. I.e if Input String=The C Programming Language Output String=Language Programming C The Here is the code ..but it seems a bit "bloated" as i need an extra array of same size of the original string
16
2095
by: Scott | last post by:
Yeah I know strings == immutable, but question 1 in section 7.14 of "How to think like a computer Scientist" has me trying to reverse one. I've come up with two things, one works almost like it should except that every traversal thru the string I've gotten it to repeat the "list" again. This is what it looks like: for char in x: mylist.append(char)
3
6105
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 into the upper textbox must appear in the lower textbox, but in reverse. If the input field contains...
1
3315
by: rajkumarbathula | last post by:
Hi Could any one help me out in reversing rows/elements of DataTable or String or DataList by using any simple statement? Thanks
0
10562
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10319
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10070
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7608
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6845
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4282
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
2
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2978
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.