Jump to content
Larry Ullman's Book Forums

Scripts 6.2 And 6.3 - Printing Addresses In Hex And Decimal

Recommended Posts



I could not get script 6.2 (address.cpp) or script 6.3 (pointers1.cpp) to print out the addresses in my Dev-C++ IDE. The typecasting gave compiler errors in both cases.


The following worked for me courtesy Mr Google and Stack Overflow:

#include <cstdlib>
#include <iostream>
#include <sstream>

int main() {

	// Create some variables and pointers.
	int a = -12;
	int *addr_of_a = &a;
	unsigned long ul;   
        std::stringstream ss;
	// Print the address of a.
	std::cout << "The address of a is "
	<< addr_of_a << std::endl;  // hex value
    ss << std::hex << addr_of_a;
    ss >> ul;
    std::cout << "The address of a is " << static_cast<unsigned long>(ul) << std::endl;  // decimal value
std::cout << "Press Enter or Return to continue.\n";

	return 0;
} // End of the main() function.
I checked and the conversion from hex to decimal was correct.


Cheers from Oz.


P.S., my environment is Windows 7, 64 bit with Dev-C++ 5.8.3

Link to comment
Share on other sites

And for the char c = 'D' I had to use:

std::cout << "The address of c is "
	<<  static_cast<const void *>(&c) << "\n";   // hex
	ss3 << std::hex << static_cast<const void *>(&c);
    ss3 >> ul3;
    std::cout << "The address of c is " << static_cast<unsigned long>(ul3) << std::endl;	// decimal
Otherwise you don't get the address of the char.



Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...