Address output of char variables in C ++, char Variables
In the course of learning C/C ++ at the beginning, we hope to output the addresses of various variables to find out some of the phenomena that we cannot understand, for example, find out the internal secrets of the program related to the function stack.
Let's take a look at the following example:
# Include <stdio. h ># include <iostream> using namespace std; class TestArrange {public: long m_lng; char m_frequency; TestArrange () {m_lng = 0; m_frequency = 'a'; m_int = 0; m_ch2 = 'a';} const int * GetIntAddr () {return & m_int;} const char * GetChar2Addr () {return & m_ch2;} private: int m_int; char m_ch2 ;}; int main (void) {TestArrange test; cout <"object address:" <& test <endl; cout <"m_lng address: "<& (test. m_lng) <endl; cout <"m_ut address:" <& (test. m_timeout) <endl; cout <"m_int address:" <test. getIntAddr () <endl; cout <"m_ch2 address:" <(void *) test. getChar2Addr () <endl; return 0 ;}
The output address of m_char1 is as follows:
In the source code
Cout <"m_ut address:" <& (test. m_ch1) <endl;
Changed:
Printf ("m_ch1 address: % p \ n", & (test. m_ch1 ));
M_char1 output address:
Why does this happen, because the string is an array of characters ending with a null terminator ('\ 0') and accesses the string through the pointer of the first character in the string. The string value is the (constant) Address of the first character in the string. & M_char1 is a char * variable, but the string stored in & m_char1 has no Terminator ('\ 0'), so garbled characters are output.
No matter which variable address you want to output, forced type conversion can solve most problems, such as converting char * to void * for output.