simple string reverse problem

Hi I wrote a small string reverse program. But it is not doing what its supposed to do...

this code works fine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
	char str[]= {"I am doing reverse string"};
	int len = strlen(str);
	char* pStr = str;
	len--;
	int term = len/2;
	while(len >=  term )
	{	
		//char ep = *(pStr + len);  //line 1
		char ep = str[len];	//line 2
		
		char sp = *pStr;
		*pStr = ep;
		
		//*(pStr + len) = ep;  //line 3
		str[len] = sp;         //line 4
		
		len--;
		pStr++;
	}


but why not this one


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

	char str[]= {"I am doing reverse string"};
	int len = strlen(str);
	char* pStr = str;
	len--;
	int term = len/2;
	while(len >=  term )
	{	
		char ep = *(pStr + len);  //line 1
		//char ep = str[len];	//line 2
		
		char sp = *pStr;
		*pStr = ep;
		
		*(pStr + len) = ep;  //line 3
		//str[len] = sp;         //line 4
		
		len--;
		pStr++;
	}


Any help will be appreciated.
If str is a pointer to a C string "Hello, World!" and len is its string length, str[len]==0, but str[len-1]=='!'.
int i = 0;
char str[]= {"I am doing reverse string"};
int len = strlen(str);
char* pStr = str;
int term = len/2;
while(i <= term)//no of iterations
{
*(pStr+len) = *(pStr+i);//copy to null value
*(pStr+i) = *(pStr+len-1);
*(pStr+len-1) = *(pStr+len);
i++;
}
Topic archived. No new replies allowed.