Address output of char variables in C ++, char Variables

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.