// ExampleCodes.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
char* stringReverse(char* s)
{
char temp, *p,*q;
q = s;
while( *(++q));
for( p = s; p < --q; p++)
{
temp = *p;
*p = *q;
*q = temp;
}
return s;
}
int _tmain(int argc, _TCHAR* argv[])
{
stringReverse("StringReverse");
return 0;
}
views:
171answers:
6
+8
A:
You can't modify constant string literals.
stringReverse("StringReverse");
You could use a character array instead:
char str[] = "StringReverse";
Mark Byers
2010-09-12 23:32:54
A:
You never allocated any memory for p. You can try p = new char[sizeof(s)];
Alexander Rafferty
2010-09-12 23:33:29
`p` doesn't need its own memory - the function reverses a string in-place.
caf
2010-09-12 23:35:13
Okay, my mistake. His function doesn't seem to make much sense to me. I think that it could be changed to be make more clear.
Alexander Rafferty
2010-09-12 23:37:05
+5
A:
String literals, like "StringReverse", are not allowed to be modified in C. Use an array:
char str[] = "StringReverse";
stringReverse(str);
Note that your stringReverse() function has undefined behaviour if you feed it a zero-length string.
caf
2010-09-12 23:34:16
A:
Perhaps you should write something like this:
// in - string to reverse
// out - buffer for reversed string
// l - size of in
StringReverse(char* in, char* out, int l) {
for (int i=0;i<l;i++) {
out[l-(i+1)] = in[i];
}
}
*There is very very little to no speed difference between [] and *(p++) / *(p--)
Alexander Rafferty
2010-09-13 00:00:47
A:
Well I was going to clean up the awful source in the OP but instead I'll just post a cleaner version:
#include <stdio.h>
#include <string.h>
void reverse_string(char *s)
{
char *q = s + strlen(s);
for (char *p = s; p < --q; p++)
{
char temp = *p;
*p = *q;
*q = temp;
}
}
int main()
{
char s[] = "StringReverse";
reverse_string(s);
puts(s);
return 0;
}
I hope for your sake Amit that you're still a student.
Update0
This is actually pure C, so learn from and awe at its performance but don't start writing C++ like this.
Matt Joiner
2010-09-13 03:12:21
I'm half tempted to downvote for "cleaning up" code, and then adding an xor hack.
Dennis Zickefoose
2010-09-13 03:22:34
I'm half-tempted to downvote just for the xor hack. Unless you've got a benchmark showing that xor is universally faster than using a temporary, don't bother with it.
greyfade
2010-09-13 03:25:04
@Matt: Still, this is a C++ question. What's with `std::swap(*p,*q)`? And in C++, those headers should be `<cstdio>` and `<cstring>`, and it's `std::strlen()`.
sbi
2010-09-13 21:08:15
@sbi: Yeah that's true. Suddenly I don't feel like doing C++ (that was quick, I hadn't started yet) ;]
Matt Joiner
2010-09-14 02:37:13