C语言 c 中与平台无关的 size_t 格式说明符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2125845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:14:25  来源:igfitidea点击:

Platform independent size_t Format specifiers in c?

cplatform-independentsize-tformat-stringformat-specifiers

提问by Ethan Heilman

I want to print out a variable of type size_tin C but it appears that size_tis aliased to different variable types on different architectures. For example, on one machine (64-bit) the following code does not throw any warnings:

我想size_t在 C 中打印出一个类型的变量,但它似乎size_t是不同架构上不同变量类型的别名。例如,在一台机器(64 位)上,以下代码不会抛出任何警告:

size_t size = 1;
printf("the size is %ld", size);

but on my other machine (32-bit) the above code produces the following warning message:

但在我的另一台机器(32 位)上,上面的代码产生以下警告信息:

warning: format '%ld' expects type 'long int *', but argument 3 has type 'size_t *'

警告:格式“%ld”需要类型“long int *”,但参数 3 的类型为“size_t *”

I suspect this is due to the difference in pointer size, so that on my 64-bit machine size_tis aliased to a long int("%ld"), whereas on my 32-bit machine size_tis aliased to another type.

我怀疑这是由于指针大小的不同,所以在我的 64 位机器size_t上别名为 a long int( "%ld"),而在我的 32 位机器size_t上别名为另一种类型。

Is there a format specifier specifically for size_t?

是否有专门用于的格式说明符size_t

回答by Adam Rosenfield

Yes: use the zlength modifier:

是:使用z长度修饰符:

size_t size = sizeof(char);
printf("the size is %zu\n", size);  // decimal size_t ("u" for unsigned)
printf("the size is %zx\n", size);  // hex size_t

The other length modifiers that are available are hh(for char), h(for short), l(for long), ll(for long long), j(for intmax_t), t(for ptrdiff_t), and L(for long double). See §7.19.6.1 (7) of the C99 standard.

其他可用的长度修饰符是hh(for char)、h(for short)、l(for long)、ll(for long long)、j(for intmax_t)、t(for ptrdiff_t) 和L(for long double)。请参阅 C99 标准的 §7.19.6.1 (7)。

回答by maxschlepzig

Yes, there is. It is %zu(as specified in ANSI C99).

就在这里。它是%zu(在 ANSI C99 中指定)。

size_t size = 1;
printf("the size is %zu", size);

Note that size_tis unsigned, thus %ldis double wrong: wrong length modifier and wrong format conversion specifier. In case you wonder, %zdis for ssize_t(which is signed).

请注意,它size_t是无符号的,因此%ld是双重错误:错误的长度修饰符和错误的格式转换说明符。如果您想知道,%zdis for ssize_t(已签名)。

回答by Arkantos

MSDN, says that Visual Studio supports the "I" prefix for code portable on 32 and 64 bit platforms.

MSDN说,Visual Studio 支持在 32 位和 64 位平台上移植代码的“I”前缀。

size_t size = 10;
printf("size is %Iu", size);