473,804 Members | 3,185 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
Hi,

See inlines

Kind regards.

sl*******@yahoo .com wrote:
tmp123 wrote:

Oh wow, tested it and it does work. I've always thought that "start of
block" refers to the start of the function. Learn something new
everyday. This is indeed nice as localising scope is usually a "good
thing"(tm).

"works" only "more or less". Imagine you have a function with two big
locals.The first one is used at the start of function, the second one
at the end. You can thing this version saves stack space:

void test ( void )
{
{
char tmp1[10000];
... some code
}
{
char tmp2[10000];
... more code
}
}

However, if you display the address of tmp1 and tmp2, you will see that
lots of compilers converts it to:
void test ( void )
{
char tmp1[10000];
char tmp2[10000];
... some code
... more code
}


At the assembly level maybe but at the "C" level not true. Try
compiling:

#include <stdio.h>
int main()
{
int i;
for (i=0;i<10;i++) {
int n = i * 2;
printf("%d\n", n);
}
n = 3;
printf("%d\n", n);
}

and you'll get:

testprog.c: In function `main':
testprog.c:14: error: `n' undeclared (first use in this function)
testprog.c:14: error: (Each undeclared identifier is reported only once
testprog.c:14: error: for each function it appears in.)


Thanks for showing the difference between variable scope, visibility,
life... . It can be interesting for some readers.

Localising scope has little to do with trying to save memory but have
more to do with protecting variables from being misused. Think of the
difference of local and global, only in this case we get to use
variables that are more 'local' than local (if you know what I mean).

See this function:

/* swap pairs of characters in strings: 12345 => 21435 */
void reverse ( char *s )
{
/* end condition */
if ( s[0]=='\0' || s[1]=='\0' ) return;

/* swap values */
{
char tmp;
tmp=s[0];
s[0]=s[1];
s[1]=tmp;
}

reverse(s+2);
}

The first language I encountered this feature is in Perl. Little did I
know that C had it all along.


There are older languages than perl with it.

Kind regards.

Jan 1 '06 #41
tmp123 a écrit :
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.


The effect is similar. What exactly is your point ?
2) Not always a stack to add variables is available,
Correct, but a C implementation requires automatic memory space for the
purpose. If there is no automatic memory available, the implementation
is not compliant.
or to add more
variables to it. Sometimes only modify code is allowed (i.e: patching
firmware in real time systems without stop them).
Sounds to be a twisted way of thinking...
3) Relation between names "i" and "j" and their meaning/usage is
totally lost.
Ok, I could have used ir and iw instead (standing for read/write indexes).
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).


It's debatable. I personally prefer to use the for() constructs for
'canonic' loops

for (i = 0; i < n; i++)

For other usages (like the one here), I find while() more appropriate,
specially at debug stage.
{
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).


I failed to understand your point. What exactly is wrong here ? All I
could say is that I should have used int instead of char.
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.


So what ? It seems that you are having hard time to find a real failiure
in Christian's code. Never mind, making a fool of yourself in public was
definitely your choice.

--
A+

Emmanuel Delahaye
Jan 2 '06 #42
tmp123 a écrit :
"works" only "more or less". Imagine you have a function with two big
locals.The first one is used at the start of function, the second one
at the end. You can thing this version saves stack space:

void test ( void )
{
{
char tmp1[10000];
... some code
}
{
char tmp2[10000];
... more code
}
}

However, if you display the address of tmp1 and tmp2, you will see that
lots of compilers converts it to:
void test ( void )
{
char tmp1[10000];
char tmp2[10000];
... some code
... more code
}

that is not the expected one. That doesn't means this resource must not
be used. But it is good to known what will happen.


This is completely a compiler issue. The C language semantics allows the
optimization, but the implementors are free to optimize or not.

--
A+

Emmanuel Delahaye
Jan 2 '06 #43
Emmanuel Delahaye wrote:
tmp123 a écrit :

[...]
2) Not always a stack to add variables is available,
Correct, but a C implementation requires automatic memory space for the
purpose. If there is no automatic memory available, the implementation
is not compliant.
or to add more
variables to it. Sometimes only modify code is allowed (i.e: patching
firmware in real time systems without stop them).


Sounds to be a twisted way of thinking...


No, it sounds like a real situation. Imagine you have a lot of machines
controling some public service of your country. Imagine these machines
have one process with lots of threads, each one controlling one user
session. Now, ops, you find an error on code: two variables must be
swap.

What you do? Stop all country? Update a few code is easy, but better
not to change in a live system the stack structure. Thus, use a trick
like a^=b^... could be the difference between a big problem and a
critical problem.

Moreover, in the previous post there was a lot of person saying "to
swap you need a local variable". Well, like it is explained in the
first level of any good programming course, there are more options.
3) Relation between names "i" and "j" and their meaning/usage is
totally lost.
Ok, I could have used ir and iw instead (standing for read/write indexes).


They are perfectly logical names... taking into account we are talking
about a swap of data!
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).


It's debatable. I personally prefer to use the for() constructs for
'canonic' loops

for (i = 0; i < n; i++)

For other usages (like the one here), I find while() more appropriate,


It seems you know more than the authors of C. Why not remove the "for"
syntax and change it to "for <lv> = 1 TO <expr>". It is preferable for
you?.
specially at debug stage.
And after debug you modify code?


So what ? It seems that you are having hard time to find a real failiure
in Christian's code. Never mind, making a fool of yourself in public was
definitely your choice.
But never ignorant.

--
A+

Emmanuel Delahaye


Kind regards.

Jan 2 '06 #44
tmp123 wrote:
Emmanuel Delahaye wrote:
tmp123 a écrit :
[...]
2) Not always a stack to add variables is available,

Correct, but a C implementation requires automatic memory space for the
purpose. If there is no automatic memory available, the implementation
is not compliant.
or to add more
variables to it. Sometimes only modify code is allowed (i.e: patching
firmware in real time systems without stop them).

Sounds to be a twisted way of thinking...


No, it sounds like a real situation. Imagine you have a lot of machines
controling some public service of your country. Imagine these machines
have one process with lots of threads, each one controlling one user
session. Now, ops, you find an error on code: two variables must be
swap.


How often do you come across a bug where the correct action is just to
swap to variables? I've come across lots of bugs but can't think of a
time when it was a bug significant to require a live patch where that
would solve it.
What you do? Stop all country? Update a few code is easy, but better
not to change in a live system the stack structure. Thus, use a trick
like a^=b^... could be the difference between a big problem and a
critical problem.
So how are you going to actually change the code on this running system
without breaking it? Especially as it is highly unlikely to be in a
place where you have left a load of noops in that you can just
overwrite. If there are, then you can just read one, push it on the
stack, move the other, and pop the one you save off and write it back.
I've yet to come across any situation when that would not be acceptable.
Mind you, as I say, the chances of you being able to patch the code for
for that on a live system are negligible.

BTW, I have been involved in patching live systems, but it was where we
knew there was the possibility of needing to patch things and we could
design things in such a way as to specifically allow it. It also
required working at the assembler level rather than in C, and I can't
see how the tricks we applied could be used at the C level.
Moreover, in the previous post there was a lot of person saying "to
swap you need a local variable". Well, like it is explained in the
first level of any good programming course, there are more options.


In assembler programming it might sometimes make sense to use another
method, I've yet to see an instance where it would have made sense in
any higher level language, including in C.

<snip>
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).

It's debatable. I personally prefer to use the for() constructs for
'canonic' loops

for (i = 0; i < n; i++)

For other usages (like the one here), I find while() more appropriate,


It seems you know more than the authors of C. Why not remove the "for"
syntax and change it to "for <lv> = 1 TO <expr>". It is preferable for
you?.


Because then you could not do a list traversal for loop possibly.
Anyway, since no one uses every facility of any language, it should
harldy be a surprise when someone says they would not use a particular
facility in some specific way.
specially at debug stage.


And after debug you modify code?


I doubt he would.
So what ? It seems that you are having hard time to find a real failiure
in Christian's code. Never mind, making a fool of yourself in public was
definitely your choice.


But never ignorant.


Actually, you do sound ignorant. Whether you are or not is a completely
different matter.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Jan 2 '06 #45
"tmp123" <tm****@menta.n et> writes:
Emmanuel Delahaye wrote:
tmp123 a écrit : [...]
> or to add more
> variables to it. Sometimes only modify code is allowed (i.e: patching
> firmware in real time systems without stop them).
Sounds to be a twisted way of thinking...


No, it sounds like a real situation. Imagine you have a lot of machines
controling some public service of your country. Imagine these machines
have one process with lots of threads, each one controlling one user
session. Now, ops, you find an error on code: two variables must be
swap.

What you do? Stop all country? Update a few code is easy, but better
not to change in a live system the stack structure. Thus, use a trick
like a^=b^... could be the difference between a big problem and a
critical problem.


I can imagine the need to patch live code under some circumstances,
but doing so is not C programming.

It's conceivable, I suppose, that in the process of doing so you might
need to use the xor trick to swap two variables, but it hardly seems
likely.
Moreover, in the previous post there was a lot of person saying "to
swap you need a local variable". Well, like it is explained in the
first level of any good programming course, there are more options.


Sure, there are more options, but no better ones. The dangers of the
xor trick are explained in the C FAQ. Some CPUs may have swap
instructions, but there's no direct way to use them from C (though a
decent optimizing compiler should be able to generate one from the
obvious code).

The way to swap two variables in C is:
temp = x;
x = y;
y = x;
If you feel the need to use some other method, you should explain why
the obvious technique won't work for you.

[...]
So what ? It seems that you are having hard time to find a real failiure
in Christian's code. Never mind, making a fool of yourself in public was
definitely your choice.


But never ignorant.


Never? I find that difficult to believe. My own areas of ignorance
are vast (though I try to acknowledge them); I would expect the same
of any finite being.

--
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.
Jan 2 '06 #46
Albert wrote:
char s[5];

s[0] = 'h';
s[1] = 'e';
s[2] = 'l';
s[3] = 'l';
s[4] = 'o';


That's not a string.

/* BEGIN new.c */

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

char *str_rev(char *s);

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

puts(str_rev(s) );
return 0;
}

char *str_rev(char *s)
{
char *t, swap;
char *const p = s;

if (*s != '\0') {
t = s + strlen(s + 1);
while (t > s) {
swap = *t;
*t-- = *s;
*s++ = swap;
}
}
return p;
}

/* END new.c */
--
pete
Jan 4 '06 #47

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
9704
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
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
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...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
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
5508
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
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.