簡體   English   中英

為什么printf()在C ++指針中顯示與cout不同的地址輸出?

[英]Why does printf() display a different address output than cout in C++ pointers?

#include <iostream>
#include <cstdio>
#include <cmath>

using namespace std;

int main(){

    int x = 25;
    int y = 35;

    int *p0 = &x; 
    int *p1 = &y;

    cout << p0 << endl; 

    printf("%x",p0); 

    cin.get();
    return 0;
}

printf()顯示22fd6c的內存地址輸出

cout顯示內存地址輸出0x22fd6c

只是想知道這是否重要,如果有的話,是否有任何方法可以解決它。

因為您使用%x作為格式說明符,這意味着unsigned int十六進制格式(不帶0x )。 它與您機器中不同格式的數字相同,但在64位機器中,對象指針通常有8個字節,您可能可能使用不同的數字。

指針的正確格式說明符是%p ,它以實現定義的方式打印指針,通常以0x為前綴,試試這個:

printf("%p\n", static_cast<void *>(p0));

請注意, %p需要void *指針,因此需要進行強制轉換。

它是相同的,0x只是一個前綴,用於表明它是一個十六進制數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM