c string question

i have a question that confusing me alot
we know in c++ to declare an pointer-based string we use the code
1
2
char * ptr;
cin>>ptr; 

but my question is that we know if i write

cout<<ptr;
this must output the location that ptr pointed to
but here the confusing is this code will output the string that pointer hold
why ??
I do hope you made that pointer point to something before you wrote to the location it points to.

std::cout interprets passing pointers to char, and only pointers to chars, as the intention to print the C string they point to. If you need to print the actual address, cast the pointer to anything. void *, for instance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include "stdafx.h"
#include "iostream";
using namespace std;
void swap (char  * , int n);
int _tmain(int argc, _TCHAR* argv[])
{
int size;
char *string="hello" ;
cout<<"input string =";
cin>> string ;
for(size=0 ; *(string+size)!='\0' ;size++);

reverse(string,size);
cout<<"string after reverse:\t"<<string<<"\n";

	return 0;
}
void reverse (char*  string , int n)
{

char *swap = string+n-1;
*str = string;
for (int i=0;i<=n/2-1;i++)
	{
	char temp =*(swap-i);
	*(swap-i)=*(str+i);
	*(str+i)=temp;
	}

}

i wrote this program to reverse a string and as you see i used pointers here , but the program still doesn't work ?? can you help me i have seen that pointer str didn't point to the first char but it points to all the string while swap points to the last character int the string and when compiler reach to this line
*(swap-i)=*(str+i);
the program return a run time error
Last edited on
Line 8 is wrong... you need to make a char array instead.

Line 8 is wrong... you need to make a char array instead.

thank you but can you tell me why the code above is incorrect ? ididn'tt get the idea here
Topic archived. No new replies allowed.