C/C++ 中指针地址输出


姿势很多

#include <iostream>
using std::cout;
using std::endl;
int main()
{
    const char *pszStr = "this is a string";
    // 输出字符串
    cout << "字符串:" << pszStr << endl;
    // 显然不会输出地址值
    cout << "字符串起始地址值: " << pszStr << endl;
    return 0;
}
#include <stdio.h>
int main()
{
    const char *pszStr = "this is a string";
    // 输出字符串\
    printf("字符串:%s\n", pszStr);
    // 输出地址值
    printf("字符串起始地址值:%p\n", pszStr);
    return 0;
}

C++标准库中I/O类对<<操作符重载,因此在遇到字符型指针时会将其当作字符串名来处理,输出指针所指的字符串。既然这样,那么我们就别让它知道那是字符型指针,所以得用到强制类型转换,不过不是C的那套,我们得用static_cast来实现,把字符串指针转换成无类型指针,这样更规范,如下:

#include <iostream>
using std::cout;
using std::endl;
int main()
{
    const char *pszStr = "this is a string"; 
    // 输出字符串
    cout << "字符串:" << pszStr << endl;            
    // 如我们所愿,输出地址值
    cout << "字符串起始地址值: " << static_cast<const void *>(pszStr) << endl;
    return 0;
}

使用 %zu

int i = 1;
int *p = &i;
printf("Printing p: %%p = %p, %%zu = %zu\n", p, p);

Pre-defined

Convert to the uintptr_t type defined in <stdint.h> and format with the PRIuPTR specifier defined in <inttypes.h>:

#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    printf("%" PRIuPTR "\n", (uintptr_t) &argc);
}

Cast the pointer to uintmax_t (defined in <stdint.h>), and print the cast result with %ju:

printf("Printing p: %%p = %p, %%ju = %ju\n", p, (uintmax_t)p);

Note that there is no guarantee that uintmax_t is wide enough to hold a pointer, but it's probably OK. (If it's not OK for your platform, the compiler might complain.) You could use uintptr_t, as suggested elsewhere, but in the case that uintmax_t isn't wide enough, uintptr_t won't exist at all.

指向结构体的指针

Stack Overflow

参考


文章作者: sfc9982
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 sfc9982 !
  目录