【问题标题】:How to print an unsigned int* in c? [duplicate]如何在c中打印一个无符号的int *? [复制]
【发布时间】:2020-06-07 19:06:28
【问题描述】:

我尝试在 C 中打印 unsigned int*。我使用了 %X,但编译器说:

" 格式 %x 需要 unsigned int 类型的参数,但参数 3 的类型为 unsigned int*"。

我也使用了"%u",但我又遇到了同样的错误。

谁能帮帮我?

【问题讨论】:

  • 编译器告诉我们 100% 正确。使用%p 格式说明符打印指针类型变量。例如unsigned int *ptr = &someAddr; printf("Address %p\n", (void*)ptr);

标签: c printing unsigned-integer


【解决方案1】:

如果要打印指针,则需要使用%p 格式说明符并将参数转换为void *。类似的东西

 printf ("%p", (void *)x);

其中x 的类型为unsigned int*

但是,如果你想打印存储在x 的值,你需要取消引用它,比如

printf ("%u", *x);

【讨论】:

  • 非常感谢。你的建议很有用,解决了我的问题。
  • @Mahan — 如果这有帮助,别忘了接受它。
【解决方案2】:

如果你想打印指针本身,你应该使用格式%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 列出了所有标准格式说明符和可能的修饰符。

【讨论】:

    猜你喜欢
    • 2012-08-14
    • 2023-03-12
    • 2013-07-20
    • 2011-05-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 1970-01-01
    • 2017-03-25
    相关资源
    最近更新 更多