Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable value and its address using pointers in C++

Tags:

c++

pointers

I'm having some trouble understanding pointers. In the following code, I'm trying print the address of a variable in 2 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 thing but now using character type variable, I get some trash 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 in Advance.

like image 598
user3922546 Avatar asked Mar 19 '23 02:03

user3922546


1 Answers

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

Just cast the pointer:

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

or

cout << "address pointed by pointer" << static_cast<void*>(char_pointer) << endl;
like image 57
2501 Avatar answered Mar 28 '23 04:03

2501