如何在 c 中打印一个 unsigned int*?
How to print an unsigned int* in c?
我试图在 C 中打印一个 unsigned int*
。我使用 %X
但编译器说:
" format %x
expects argument of type unsigned int
, but argument 3 has type unsigned int*
".
我也用了"%u"
,但我又遇到了同样的错误。
有人可以帮助我吗?
如果要打印指针,需要使用 %p
格式说明符并将参数转换为 void *
。像
printf ("%p", (void *)x);
其中 x
的类型为 unsigned int*
。
但是,如果你想打印存储在 x
的值,你需要取消引用它,比如
printf ("%u", *x);
如果你想打印指针本身,你应该使用格式 %p
:
// Create a pointer and make it point somewhere
unsigned int *pointer = malloc(sizeof *pointer);
// Print the pointer (note the cast)
printf("pointer is %p\n", (void *) pointer);
或者如果你想打印指针指向的值,那么你需要取消引用指针:
// Create a pointer and make it point somewhere
unsigned int *pointer = malloc(sizeof *pointer);
// Set the value
*pointer = 0x12345678;
// And print the value
printf("value at pointer is %08X\n", *pointer);
虽然 %p
格式说明符并不常见,但大多数体面的书籍 类 和教程应该包含有关取消引用指针以获取值的信息。
我也推荐例如this printf
(and family) reference 其中列出了所有标准格式说明符和可能的修饰符。
我试图在 C 中打印一个 unsigned int*
。我使用 %X
但编译器说:
" format
%x
expects argument of typeunsigned int
, but argument 3 has typeunsigned int*
".
我也用了"%u"
,但我又遇到了同样的错误。
有人可以帮助我吗?
如果要打印指针,需要使用 %p
格式说明符并将参数转换为 void *
。像
printf ("%p", (void *)x);
其中 x
的类型为 unsigned int*
。
但是,如果你想打印存储在 x
的值,你需要取消引用它,比如
printf ("%u", *x);
如果你想打印指针本身,你应该使用格式 %p
:
// Create a pointer and make it point somewhere
unsigned int *pointer = malloc(sizeof *pointer);
// Print the pointer (note the cast)
printf("pointer is %p\n", (void *) pointer);
或者如果你想打印指针指向的值,那么你需要取消引用指针:
// Create a pointer and make it point somewhere
unsigned int *pointer = malloc(sizeof *pointer);
// Set the value
*pointer = 0x12345678;
// And print the value
printf("value at pointer is %08X\n", *pointer);
虽然 %p
格式说明符并不常见,但大多数体面的书籍 类 和教程应该包含有关取消引用指针以获取值的信息。
我也推荐例如this printf
(and family) reference 其中列出了所有标准格式说明符和可能的修饰符。