6/26/2019 0 Comments Reverse A String In CI want to use pointers to reverse a char array in C++. I was wondering if there is anything that I should do differently? Am I doing this correctly? Is there a more efficient way to accomplish this? My small program: Almost every programmer needs to write a function to reverse a given string and this exercise is kinda a favourite question in first round interviews. To reverse a string, e.g., the source string is abcd and the output string should be dcba. This article will present a few piece of C/C functions that illustrate different approaches to do this task.
AlexAlex
5 Answersif you're supposed to write a loop, or, of course, if you can use a C++ string,
PotatoswatterPotatoswatter
Assuming you can't use anything but C string functions, I would
So something like:
visitorvisitor
You could use Heck, you could just use Well, actually, a tiny nit: if
ephemientephemient
Nothing really wrong with yours I would stay away from using well know type names as variables like string for example as it makes it confusing for others to read. Just for one more way you can do it. However like stated above you almost always want to use a library function over your own code if you can find one(you have no idea how many times I've seen professional programmers writing code that exists in a standard library when it could have easily been discovered with a Google search but I digress.
rerunrerun
Your code is very verbose and enumerates every operation, like picking the length of the string or assigning pointer to the end of the string or using a helper variable for exchanging values. There are many ways to make it more efficient (as other answers prove), but arguably more correctly. Your solution puts code clarity ahead of performance and that is a praise worthy habit. Of course the code could be written in half as many instructions, but optimizing compiler will do pretty much the same work off your code (one could shed a couple of cycles by some clever coding), but your is simply more readable. Of course if you really want some extreme performance boost (but on much longer strings, megabytes of data maybe), this is a perfect job for the GPU. It would use 50 times as much time to set up the operation, then a tiny fraction of current CPU time to perform it.
SF.SF.
Not the answer you're looking for? Browse other questions tagged c++pointersarrays or ask your own question.I have developed a reverse-string program. I am wondering if there is a better way to do this, and if my code has any potential problems. I am looking to practice some advanced features of C.
ant2009ant2009
23 AnswersIf you want to practice advanced features of C, how about pointers?We can toss in macros and xor-swap for fun too! A pointer (e.g. We can do simple arithmetic with pointers. When we increment (or decrement)a pointer, we simply move it to refer to the next (or previous)memory location for that type of value. Incrementing pointers ofdifferent types may move the pointer by a different number ofbytes because different values have different byte sizes in C. Here, we use one pointer to refer to the first unprocessed To do the swapping, I've defined a macro. Macros are text substitutiondone by the C preprocessor. They are very different from functions,and it's important to know the difference. When you call a function,the function operates on a copy of the values you give it. When you calla macro, it simply does a textual substitution - so the arguments you giveit are used directly. Since I only used the Note that the macro arguments show up once for each time they're used in the macro definition. This can be very useful - but can also break your codeif used incorrectly. For example, if I had compressed the increment/decrementinstructions and the macro call into a single line, like Then this would expand to Which has triple the increment/decrement operations, and doesn't actuallydo the swap it's supposed to do. While we're on the subject, you should know what xor ( A well known trick is to use xor to swap two values. This works because of three basicproperties of xor: So the values are swapped. This does have one bug - when Since we While we're concerned about correctness we should check our edge cases. The There's a bunch of C to explore. Have fun with it! Update:mmw brings up a good point, which is you do have to be slightly careful how you invoke this, as it does operate in-place. This works fine, since Will cause your code to flame and die at runtime. That's because There are some hacks you could try to make sure that some memory is on the stack or in the heap (and is therefore editable), but they're not necessarily portable, and it could be pretty ugly. However, I'm more than happy to throw responsibility for this to the function invoker. I've told them that this function does in place memory manipulation, it's their responsibility to give me an argument that allows that.
Community♦
rampionrampion
Just a rearrangement, and safety check. I also removed your non-used return type. I think this is a safe and clean as it gets: Edited so that end will not point to a possibly bad memory location when strlen is 0.
GManNickGGManNickG
Michael BurrMichael Burr
This complete program shows how I would do it. Keep in mind I was writing C when most of you whippersnappers were a glint in your mothers eyes so it's old-school, do-the-job, long-var-names-are-for-wimps. Fix that if you wish, I'm more interested in the correctness of the code. It handles NULLs, empty strings and all string sizes. I haven't tested it with strings of maximum size (max(size_t)) but it should work, and if you're handling strings that big, you're insane anyway :-) The output of that is:
paxdiablopaxdiablo
RossFabricantRossFabricant
You could change your for loop declaration to make the code shorter:
Ben StraubBen Straub
Does nobody use pointers anymore? EDIT: Sorry, just noticed the above XOR example...
Sanjaya RSanjaya R
I don't see a return statement, and you are changing the input string, which may be a problem for the programmer. You may want the input string to be immutable. Also, this may be picky, but len/2 should be calculated only one time, IMO. Other than that, it will work, as long as you take care of the problem cases mentioned by rossfabricant.
James BlackJames Black
kevinkevin
resultswayresultsway
This solution is based on GManNickG's post with a few modifications. The initial logical statement may be dangerous if !str is not evaluated before the strlen operation (For a NULL ptr). This wasn't the case with my compiler. I thought I would add this code because its a nice example of a do-while loop.
TheRealSheldonTheRealSheldon
Since you say you want to get fancy, perhaps you'll want to exchange your characters using an XOR swap.
chaoschaos
Rather than breaking half-way through, you should simply shorten your loop.
dreamlaxdreamlax
kyle kkyle k
KevinKevin
deepak kumar routdeepak kumar rout
siken.dongolsiken.dongol
The code looks unnecessarily complicated. Here is my version:
Alex RichardsonAlex Richardson
Dev_GodDev_God
Деян ДобромировДеян Добромиров
Here is my shot. I avoid swapping just by using the standard and here a running example.
gon1332gon1332
My two cents: Test #1 – Test #2 –
madmurphymadmurphy
That's a good question ant2009. You can use a standalone function to reverse the string. The code is...
SDAHSDAH
Not the answer you're looking for? Browse other questions tagged cstringpointers or ask your own question.
0 Comments
Leave a Reply. |