The value of a variable and its address using pointers in C ++

I'm having trouble understanding pointers. In the following code, I try to print the address of a variable in two ways: once using the address operator, and then using pointers:

#include<iostream>
using namespace std;
int main (void)
{
    int x = 10;
    int *int_pointer;
    int_pointer = &x;
    cout << "x address=" << &x << endl;
    cout << "x address w pointer=" << int_pointer << endl;
    return 0;
}
x address = 0028FCC4
x address w pointer = 0028FCC4

This works as expected. But when I do the same, but now I use a variable like symbol, I get some garbage output:

#include<iostream>
using namespace std;
int main(void)
{
    char c = 'Q';
    char *char_pointer;
    char_pointer = &c;
    cout << "address using address operator=" << &c << endl;
    cout << "address pointed by pointer=" << char_pointer << endl;
    return 0;
}
address using address operator=Q╠╠╠╠£åbªp é
address pointed by pointer=Q╠╠╠╠£åbªp é

I have no idea why this is happening. Thanks at Advance.

+4
source share
3 answers

The C ++ library overloads the <operator for certain types. (char *) is one of them. Cout tries to print a string, an array of characters ending in a null character.

Just enter the pointer:

cout << "address pointed by pointer" << ( void* )char_pointer << endl;

or

cout << "address pointed by pointer" << static_cast<void*>(char_pointer) << endl;
+7

2501, &c, c char, a char *, , '\0' std::cout, , .

, , (void *), 2501.

+1

, , , char , , , , . , , ASCII, , ostream . , , static_cast. :

cout << "address pointed by pointer=" << static_Cast<void*>(char_pointer) << endl;
0

All Articles