#include <iostream>
#include <cstring>

void rev(const char* str)
{
	char* p = new char[strlen(str) + 1];
	for(int i = 0; str[i] != '\0'; i++)
	{
		p[i] = str[strlen(str) - i];
	}
	p[strlen(p) + 1] = '\0';
	std::cout << p;
}

int main()
{
	const char* s = "vBx";
	rev(s);
}

What its wrong here ? it doesnt output.

Recommended Answers

All 5 Replies

The first thing that is wrong is that you have written this: p[i]=str[strlen(str)-i]; Now apart from re-using strlen(str), which it would have been better to put it in a varaible (although my compiler nicely optimized it out). What happens when you put i==0 into that statement you get: p[0]=str[strlen(str)]; and that is the same as p[0]=0; .

Line p[strlen(p)+1]=0; is also not good, if you had done your loop
correctly, this code would have been horrible, since you don't know the length of p.
[The code adds a 0 after the final zero]

If you get into char string problems, it often pays to do this
for(int

Try using a temporary variable :

for(i = 0, j = strlen(a) - 1;i < j; i++, j--) {
                t = a[i];
                a[i] = a[j];
                a[j] = t;
}
#include <algorithm>
void reverse(char* str)
{
   std::reverse(str, str+strlen(str));
}
commented: ha =D +6

@^

i guess the OP needed to implement his own function.

OK, I guess you're right, in which case I guess your solution is best :)
Best Regards

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.