姿势很多
1 2 3 4 5 6 7 8 9 10 11 12 #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 ; }
1 2 3 4 5 6 7 8 9 10 #include <stdio.h> int main () { const char *pszStr = "this is a string" ; printf ("字符串起始地址值:%p\n" , pszStr); return 0 ; }
C++标准库中I/O类对<<操作符重载,因此在遇到字符型指针时会将其当作字符串名来处理,输出指针所指的字符串。既然这样,那么我们就别让它知道那是字符型指针,所以得用到强制类型转换,不过不是C的那套,我们得用static_cast来实现,把字符串指针转换成无类型指针,这样更规范,如下:
1 2 3 4 5 6 7 8 9 10 11 12 #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
1 2 3 int i = 1 ;int *p = &i;printf ("Printing p: %%p = %p, %%zu = %zu\n" , p, p);
Pre-defined
1 2 3 4 5 6 7 8 9 10 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:
1 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
参考