#include<iostream>
#include<fstream>

using namespace std;

int main()
{
  char a='p';
  int b=23;
  float c=45.67;
  ofstream out("test.txt");

  out<<a<<" "<<&a<<endl;
  out<<b<<" "<<&b<<endl;
  out<<c<<" "<<&c<<endl;
}

the output for this is in the text file:

p pα#a/
23 0x22cd08
45.67 0x22cd04

why is the address of the character variable is very different from others??
could some one pls explain this!!

Recommended Answers

All 4 Replies

What happens here:

char* a = "Hello world";
cout << a;

a is a char*, so cout starts printing until it finds a null character.
It prints Hello World.

char a = 'p';
cout << &a;

a is a char, but &a is also a char* just like in the last example.
So cout prints the p, and then whatever is after the p in memory until it finds a null byte.

thank you for your reply.. can you pls tell me how to get the address of the character variable "a"..

The question is why you would want to know the exact location of variable char a. It's useless as when the variable is initialized with the onset of the program, the variable will be in a different memory location. Hence, hard coding memory locations will be meaningless.

#include<iostream>
      using namespace std;
 
  int main(){


char a='p';
char *point;

point = &a;        // point =  memory location of char a

cout << a << " - " << &a << endl;
cout << *point << " - " << point << endl;

/* This will only move up or down one memory location at a time, not necessarily moving up or 
down one character variable location. */

cout << "Moving down one memory location.\n";
point --;
cout << *point << " - " << point << endl;
cout << "Moving up one memory location.\n";
point++;
cout << *point << " - " << point << endl;

/* To move up and down an array, such as an array of characters (char), you will want to reference
your pointer as such*/

char b[10];
int index;

for(index = 0; index < 10; index++)		// change array b to have some comprehensible character
	b[index] = 'a' + index;

point = b;					// point points to location b[0];
cout << point[1] << endl;			// output location 2 (TWO) in the array
cout << b[1] << endl;				// point[1] should be equal to b[1];

point = b;

			
return 0;


      }
Member Avatar for embooglement

To get std::ostreams like std::cout to print pointers to characters as addresses rather than as c-style strings, typecast them to another pointer type, like so: "cout << (void*)&a << endl;"

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.