Here i have to define a function which will reverse a c-styled string.
I have made 2 functions one using dynamic memory and the other not using dynamic memory.

I would like to know of any improvements that can be made in the code.
I would also like you to comment on my Style of Writing the program.

For some reason the code-tag isnt working(OFFTOPIC)
I have used it a lot of times so i am a little confused.

#include <iostream>
#include <cstring>

void rev(char *);
void rev2(char *);

int main()
{
char str[]="I Love C++2";
rev(str);
std::cout<<str<<"\n";
rev2(str);
std::cout<<"Second : "<<str<<'\n';
}

void rev(char *p)
{
    int length=strlen(p);
    char *temp=new  char[length];
    char *index=temp;
    for(int a=0;a<=length-1;a++)
    {
    index[a]=p[(length-1-a)];
    }
    index[length]=0;
    strcpy(p,temp);
    delete [] temp;
}

void rev2(char *p)
{   
    char *q=&p[strlen(p)-1];
    char *r=p;
    while(q>r)
    {
    char s=*q;
    *q=*r;
    *r=s;
    q--;
    r++;
    }
}

>For some reason the tag isnt working(OFFTOPIC) Did you type the word 'code' in uppercase ?[code=c++] tag isnt working(OFFTOPIC)
Did you type the word 'code' in uppercase ?

For some reason the code-tag isnt working(OFFTOPIC)

Did you type the word 'code' in uppercase ?

I dint type it in uppercase and now its configured thanks.

Why using dynamic memory allocation?
You could simply do something like this:

void reverse(char p[])
{
	int len=strlen(p);
	char t;
	for(int i=(--len), j=0; i>len/2; i--, j++)
	{
		// exchange elements
		t=p[i];
		p[i]=p[j];
		p[j]=t;
	}
}

You cannot make mistakes (in the use of pointers :P) if you use this approach ...

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.