C: printf 中的 ptrdiff_t 应该使用哪个字符?

发布于 2024-12-12 17:44:50 字数 290 浏览 0 评论 0原文

printf 中的 ptrdiff_t 应该使用哪个字符?

C标准是否清楚地解释了如何在printf中打印ptrdiff_t?我还没有找到任何人。

int a = 1;
int b = 2;

int* pa = &a;
int* pb = &b;

ptrdiff_t diff = b - a;

printf("diff = %?", diff); // % what?

Which character should be used for ptrdiff_t in printf?

Does C standard clearly explains how to print ptrdiff_t in printf? I haven't found any one.

int a = 1;
int b = 2;

int* pa = &a;
int* pb = &b;

ptrdiff_t diff = b - a;

printf("diff = %?", diff); // % what?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

草莓味的萝莉 2024-12-19 17:44:52

使用%td,如果您的编译器不支持它,您应该尝试%ld(也将输入转换为long)。

Use %td and if your compiler does not support it, you should try %ld (also cast the input to long).

裂开嘴轻声笑有多痛 2024-12-19 17:44:51

这是%td。请参阅此处或更好的此处

It's %td. See here or better still here.

情话已封尘 2024-12-19 17:44:51

C11 草案解释了 7.21.6.1 7“fprintf 函数”中 ptrdiff_t 的长度修饰符

t
指定以下 diouxX 转换说明符适用于 ptrdiff_t 或相应的无符号整数类型参数;或者以下 n 转换说明符适用于指向 ptrdiff_t 参数的指针。

使用 "%td" 如下: Credit: @trojanfoe

ptrdiff_t diff = b - a;
printf("diff = %td", diff);

如果编译器不 < strong>不支持"%td",转换为有符号类型 - 越长越好。然后确保替代格式和参数匹配。

// Note the cast
printf("diff = %lld", (long long) diff); // or
printf("diff = %ld", (long) diff);

参考格式说明符

C11 draft explains the length modifier for ptrdiff_t in 7.21.6.1 7 "The fprintf function"

t
Specifies that a following d, i, o, u, x, or X conversion specifier applies to a ptrdiff_t or the corresponding unsigned integer type argument; or that a following n conversion specifier applies to a pointer to a ptrdiff_t argument.

Use "%td" as in the following: Credit: @trojanfoe

ptrdiff_t diff = b - a;
printf("diff = %td", diff);

If the compiler does not support "%td", cast to a signed type - the longer, the better. Then insure the alternative format and argument match.

// Note the cast
printf("diff = %lld", (long long) diff); // or
printf("diff = %ld", (long) diff);

Ref format specifiers

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文