473,804 Members | 3,034 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
To Mr. Keith Thompson and Mr. Tim Rentsch:

Thanks for your replies, always open to learn something new.
The first comment mades me doubt: if strlen(s)==0, s==e, thus s!=e-- is
false and exit loop.
The second comments, about sequence points, well, I must recognize I do
not know what do you refer as "sequence points". An explanation or a
reference will be welcome.

To Mr. Christian Bau:

Your English seems not to be the most valid to be used in net, because
could be easily confused with agressive, specially by non-English
people. Moreover, it could be taken as a confusion between what is a
medium to interchange knowledgment, and what is a real programming
team.

Kind regards.

Dec 30 '05 #21
"tmp123" <tm****@menta.n et> writes:
To Mr. Keith Thompson and Mr. Tim Rentsch:

Thanks for your replies, always open to learn something new.
The first comment mades me doubt: if strlen(s)==0, s==e, thus s!=e-- is
false and exit loop.


The problem is that the variable 'e' is decremented even if it is
equal to the address held in 's'. That means the decrement can
attempt to set 'e' to an address "before" the first element of
the array object holding the string, which is disallowed. It's
allowed to point to one element past the end of an array object,
but not allowed to point to one element before the beginning.
Dec 30 '05 #22
In article <11************ **********@g49g 2000cwa.googleg roups.com>,
"tmp123" <tm****@menta.n et> wrote:
To Mr. Keith Thompson and Mr. Tim Rentsch:

Thanks for your replies, always open to learn something new.
The first comment mades me doubt: if strlen(s)==0, s==e, thus s!=e-- is
false and exit loop.
The second comments, about sequence points, well, I must recognize I do
not know what do you refer as "sequence points". An explanation or a
reference will be welcome.

To Mr. Christian Bau:

Your English seems not to be the most valid to be used in net, because
could be easily confused with agressive, specially by non-English
people. Moreover, it could be taken as a confusion between what is a
medium to interchange knowledgment, and what is a real programming
team.


Nothing wrong with my english. Lots wrong with your code. I don't care
too much about the undefined behavior, because you managed to write
completely incomprehensibl e code for a very simple task.

void reverse_string (char* s)
{
int i = 0;
int j = strlen (s) - 1;

while (i < j)
{
char tmp = s [i];
s [i] = s [j];
s [j] = tmp;
++i;
--j;
}
}

works and is easy to understand.
Dec 30 '05 #23
Thanks for the explanation.

I do not know any compiler nor OS with problems for this pointer (it is
only assigned, not used, and probably the final address will be valid).
However, if you say that standard allows to pass the end of the array
but not point before, I can accept the reasoning.

Kind regards.

Dec 30 '05 #24
On 30 Dec 2005 14:10:46 -0800, in comp.lang.c , "tmp123"
<tm****@menta.n et> wrote:
I do
not know what do you refer as "sequence points". An explanation or a
reference will be welcome.
©ISO/IEC ISO/IEC 9899:1999 (E)
Annex C
(informative)
Sequence points
1 The following are the sequence points described in 5.1.2.3:
— The call to a function, after the arguments have been evaluated
(6.5.2.2).
— The end of the first operand of the following operators: logical AND
&& (6.5.13);
logical OR || (6.5.14); conditional ? (6.5.15); comma , (6.5.17).
— The end of a full declarator: declarators (6.7.5);
— The end of a full expression: an initializer (6.7.8); the expression
in an expression
statement (6.8.3); the controlling expression of a selection statement
(if or switch)
(6.8.4); the controlling expression of a while or do statement
(6.8.5); each of the
expressions of a for statement (6.8.5.3); the expression in a return
statement
(6.8.6.4).
— Immediately before a library function returns (7.1.4).
— After the actions associated with each formatted input/output
function conversion
specifier (7.19.6, 7.24.2).
— Immediately before and immediately after each call to a comparison
function, and
also between any call to a comparison function and any movement of the
objects
passed as arguments to that call (7.20.5).

(Of Christian's comment)Your English seems not to be the most valid to be used in net,


Grow a thicker skin.

Personally I also thought the code was an abhomination and had I
discovered it in a project I was running I'd have told the programmer
to remove it forthwith.

Mark McIntyre
--

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 30 '05 #25
On 30 Dec 2005 15:04:08 -0800, in comp.lang.c , "tmp123"
<tm****@menta.n et> wrote:
Thanks for the explanation.

I do not know any compiler nor OS with problems for this pointer


Thats not relevant. If it breaks the rules of the C standard, then its
not guaranteed to work, and you should not do it. One day your code
will be run on an OS which does care, and you will be fired / lose
money / lose face or whatever because of your code error.

Mark McIntyre
--

----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Dec 31 '05 #26
"tmp123" <tm****@menta.n et> writes:
Thanks for the explanation.
You're welcome, glad it was of help.

I do not know any compiler nor OS with problems for this pointer (it is
only assigned, not used, and probably the final address will be valid).
In most practical cases it won't be a problem. However, the Standard
is quite unambiguous that it is potentially a problem, and there are
some implementations (I'm pretty sure) where it fails.

However, if you say that standard allows to pass the end of the array
but not point before, I can accept the reasoning.
One way to learn about these things is to get a copy of the
Standard, and read it yourself. There's an updated version
you can get just by downloading:

http://www.open-std.org/jtc1/sc22/wg...docs/n1124.pdf

If you get a copy then you can read up on sequence points or
whatever else (including array indexing and pointer arithmetic)
and many of the comments on comp.lang.c will make a lot more
sense.

Kind regards.


Likewise. And Happy New Year.
Dec 31 '05 #27
tmp123 said:
Thanks for the explanation.

I do not know any compiler nor OS with problems for this pointer


The backroom boys are working on one right now, for all you know. And it
might just be tomorrow's sensational new toy for other, unrelated reasons.
And your boss might just say, "let's migrate all our code to this new
thing", as bosses often do. And at that point, the guys who stuck to the
rules will have working code, and the guys who didn't, won't.

So it pays to do things properly.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Dec 31 '05 #28
Hi,

See inlines:

Christian Bau wrote:
tmp123 wrote:
To Mr. Christian Bau:

Your English seems not to be the most valid to be used in net, because
could be easily confused with agressive, specially by non-English
people. Moreover, it could be taken as a confusion between what is a
medium to interchange knowledgment, and what is a real programming
team.
Nothing wrong with my english. Lots wrong with your code. I don't care
too much about the undefined behavior, because you managed to write
completely incomprehensibl e code for a very simple task.


Code that has been clearly state as "just for fun", that is, as an
academic experiment. At least, me, I get new knoledgment about pointer
before arrays and sequence points. Thanks to persons who have provided
it.

And taken into account that this piece of code has been presented as
"the good one" in a real programming team, some comments about:

void reverse_string (char* s)
{
int i = 0;
int j = strlen (s) - 1;
1) It is not the same initialize a variable as give a variable the
first value it will take.
2) Not always a stack to add variables is available, or to add more
variables to it. Sometimes only modify code is allowed (i.e: patching
firmware in real time systems without stop them).
3) Relation between names "i" and "j" and their meaning/usage is
totally lost.

while (i < j)
4) Never heard about "for" statement?. It is used to enclose in an easy
to read statement all control of the loop iterators (initialization s,
exit condition and state update).
{
char tmp = s [i];
5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).
s [i] = s [j];
s [j] = tmp;
6) It seems this code must always be compiled with latest version of
advanced compilers. The responsability to convert array index
calculations to pointer operations, even integers to pointers, is
transferred to compiler.
++i;
--j;
7) Lost lines here?
}
}

works and is easy to understand.


8) "Works" is not a measure of quality.

This is my last post in this subject. I don not like to be troll, nor
feed trolls.

Kind regards.

Dec 31 '05 #29
tmp123 wrote:
Hi,

See inlines:

Christian Bau wrote:
tmp123 wrote:
To Mr. Christian Bau:

Your English seems not to be the most valid to be used in net, because
could be easily confused with agressive, specially by non-English
people. Moreover, it could be taken as a confusion between what is a
medium to interchange knowledgment, and what is a real programming
team.
Nothing wrong with my english. Lots wrong with your code. I don't care
too much about the undefined behavior, because you managed to write
completely incomprehensibl e code for a very simple task.


Code that has been clearly state as "just for fun", that is, as an
academic experiment. At least, me, I get new knoledgment about pointer
before arrays and sequence points. Thanks to persons who have provided
it.


"For fun" still doesn't make your code correct. You stated that it
works but the experts here have pointed out that even so it is still
not correct "C". So that doesn't invalidate Mark's comments - your code
still is horrible, learn and move on.

As for your comment about Mark's tone being aggressive, you have to
learn that this is Usenet, and taking on an aggressive tone is a
tradition of the net long before you showed up. Some groups liks
comp.lang.tcl may be less aggressive but comp.lang.c is aggressive (I
learned that the hard way). Maybe it's because so many people keep
asking the same stupid questions here over and over again (and keep
making the same stupid mistakes that others have made before).
void reverse_string (char* s)
{
int i = 0;
int j = strlen (s) - 1;


1) It is not the same initialize a variable as give a variable the
first value it will take.


What are you trying to say here? That code is correct.
2) Not always a stack to add variables is available, or to add more
variables to it. Sometimes only modify code is allowed (i.e: patching
firmware in real time systems without stop them).
I don't see how this is different from your code since you yourself
introduce the variable 'r'.
3) Relation between names "i" and "j" and their meaning/usage is
totally lost.
Lost? I understood it. The code is short and clear so it is
stylistically correct to use simple variable names (n, x, y, i, j
etc..). For that matter, the "relation between" 'r' and 's' in your
code and "their meaning/usage" also fall into the same category.
while (i < j)


4) Never heard about "for" statement?. It is used to enclose in an easy
to read statement all control of the loop iterators (initialization s,
exit condition and state update).


"Easy to read"? Certainly not your code. And in Mark's code "while" is
quite natural - use the right tool for the right job.
{
char tmp = s [i];


5) Declare char here, far of the semantically parent of it (char *s) it
is only a way to hide things. And lots of compilers will ignore it (no
new frame).


This is correct and valid in C99 (unlike your code which is incorrect
and invalid in any C standard). Just because there are no C99 compilers
around doesn't mean that this code is not "C".
s [i] = s [j];
s [j] = tmp;


6) It seems this code must always be compiled with latest version of
advanced compilers. The responsability to convert array index
calculations to pointer operations, even integers to pointers, is
transferred to compiler.


Nope, the above fragment of code will compile on any C compiler, I
suspect it is even valid in the original K&R "C" but I'm not sure.
works and is easy to understand.


8) "Works" is not a measure of quality.


True, as the experts here have pointed out about YOUR code. But "easy
to understand" IS a measure of quality.
This is my last post in this subject. I don not like to be troll, nor
feed trolls.


Mark have not been acting like a troll. He was merely scolding you for
writing poor code. You however are increasingly acting in a troll like
manner by insisting to argue even when you've been proven wrong.

Dec 31 '05 #30

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
9572
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
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...
1
10303
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 most users, this new feature is actually very convenient. If you want to control the update process,...
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?
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.