beginner pointer trouble using Visual C++ 2008

Hi,

Am learning C++ from "Sams Teach Yourself C++" and I ran into a problem wihle trying to learn about pointers that isn't addressed here or in the book. I can't seem to get the pointer to a char variable to work right?
The contents of the variables work fine, but the &CVar1 and &CVar2 yields not hex address as one would hope, but rather a string special characters which I can't seem to duplicate on my keyboard here (like: a]]]]]]]]]}}}}}}}}}} only weirder). Notably both the output of &CVar1 and &CVar2 begin with the letters with which they are initialized. Any ideas? Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int main ()
{ 
	using namespace std;

	short int SVar1 = 12, SVar2 = 21	;
	int Var1 = 2, Var2 = 1	;
	char CVar1 = 'a' , CVar2 = 'g'	;
	
	cout << "Value SVar1: \t" << SVar1 << "\t address of SVar1: \t" << &SVar1 << endl	; //works as expected
	cout << "Value SVar2: \t" << SVar2 << "\t address of SVar2: \t" << &SVar2 << endl	; //works as expected
	cout << "Value Var1: \t" << Var1 << "\t address of Var1: \t" << &Var1 << endl	;  //works as expected
	cout << "Value Var2: \t" << Var2 << "\t address of Var2: \t" << &Var2 << endl	; //works as expected
	cout << "Value CVar1: \t" << CVar1 << "\t address of CVar1: \t" << &CVar1 << endl	;
	cout << "Value CVar2: \t" << CVar2 << "\t address of CVar2: \t" << &CVar2 << endl	;

	return 0	;
}
Last edited on
Hmm I had this same issue a while back when doing something like this for Homework. I never found the problem and my teacher had never heard of it either
Edit: Upon further testing it appears that cout doesn't like &CVar1 (and &CVar2) because when I create:

1
2
3
char * pCVar = &CVar1 ;
CVar2 = *pCVar ;
cout << "Now the value CVar2: \t" << CVar2 << "\t address of CVar2: \t" << &CVar2 << endl ;


and add it to the program at line 17 it does assign correctly, it just doesn't cout the address as expected. weird.
C/C++ can be a pain regarding char*.
Most C/C++ function in the standard library treats char* as a pointer to a null terminated string.
cout is no different.

So:
1
2
 char x:
cout << &x;

will try to print out a string (which might cause a segementation fault if an unitilaised char* is used) - NOT an address.

To print out char* as an address you cast it to void*

1
2
3
char* p = "Hello World";
cout << p << endl; //prints the text.
cout  << (void*)p << endl; //prints the value of the pointer 


PS
Why didn't your teacher know that??
Last edited on
Topic archived. No new replies allowed.