Jump to content
Larry Ullman's Book Forums

Scripts 6.2 And 6.3 - Printing Addresses In Hex And Decimal


Recommended Posts

Hi,

 

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";
	std::cin.get();

	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.

 

Cheers.

Link to comment
Share on other sites

 Share

×
×
  • Create New...