cout 字元指標和int等指標的解釋

來源:互聯網
上載者:User

標籤:指標

問題來源

在牛客網的討論群裡,有人提出了這樣的問題代碼:

char *p  = NULL;cout << p;******int *q = NULL;cout << q;

上述代碼在windows下面使用vs,一個會報錯一個不會報錯~ 但是在linux下面並不會報錯~

猜想
  • 字元指標是直接列印指標指向的值(字串),訪問了null 指標的內容;
  • int指標,輸出是列印指標的值(null=0),所以不會報錯.
  • 而linux下面不會報錯,那肯定是不同編譯器的處理不一樣了~
驗證
  • 程式在ubuntu14.04上跑的,使用g++
  • 並沒有去windows下面驗證,但看過別人運行類似程式的結果
    程式如下:
#include<iostream>#include<cstring>using namespace std;int main(){    char a[] = "hello,world!";    cout << "a‘s address is " << &a << endl;    char *p = a;    cout <<"the p‘s value is: " << (void *)(p) << endl;    cout << "the content is: " << p << endl;    p = NULL;    cout <<"the p‘s value is: " << (void *)(p) << endl;    cout << "the content is: " << p << endl;    if(cout.bad()) {                cout.clear();        cout << endl;        cout << "  If @p __sb is NULL, the stream will set failbit in its error state." << endl;    }    int *q = NULL;    cout <<"q‘s value is " << q << endl;    cout << "the content is " << *q << endl;    return 0;}

編譯運行:

[email protected]:~/code/C/pointer$ ./a.out a‘s address is 0xbf897d7fthe p‘s value is: 0xbf897d7fthe content is: hello,world!the p‘s value is: 0the content is:   If @p __sb is NULL, the stream will set failbit in its error state.q‘s value is 0段錯誤 (核心已轉儲)
結論


  • 如猜測的一樣, cout 的<< 在重載時,遇到char * 和int *的輸出解釋是不一樣的
  • g++在遇到Null 字元指標時,會在錯誤狀態中,置為fallbit,這個通過查看源碼是可以找到的:

/**

  • @brief Extracting from another streambuf.
  • @param __sb A pointer to a streambuf
    *
  • This function behaves like one of the basic arithmetic extractors,
  • in that it also constructs a sentry object and has the same error
  • handling behavior.
    *
    * If @p __sb is NULL, the stream will set failbit in its error state.
    *
  • Characters are extracted from @p __sb and inserted into @c *this
  • until one of the following occurs:
    *
    • the input stream reaches end-of-file,
    • insertion into the output sequence fails (in this case, the
  • character that would have been inserted is not extracted), or
    • an exception occurs while getting a character from @p __sb, which
  • sets failbit in the error state
    *
  • If the function inserts no characters, failbit is set.
    */
    __ostream_type&
    operator<<(__streambuf_type* __sb);

cout 字元指標和int等指標的解釋

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.