0
#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.

4
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by LordNemrod
0

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

Edited by StuXYZ: n/a

0

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;
}
0

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

Edited by LordNemrod: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.