与平台无关的 size_t 格式说明符在 c? ?

我想在 C 语言中打印出一个 size_t类型的变量,但是看起来 size_t在不同的体系结构中被别名为不同的变量类型。例如,在一台计算机(64位)上,下面的代码不抛出任何警告:

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

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

警告: 格式“% 1!”期望类型 ‘ long int *’,但参数3具有 “ size _ t *”

我怀疑这是由于指针大小的差异造成的,因此在我的64位机器上,size_t别名为 long int("%ld") ,而在我的32位机器上,size_t别名为另一种类型。

是否有专门针对 size_t的格式说明符?

58626 次浏览

Yes: use the z length modifier:

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), char0 (for char1), and char2 (for char3). See §7.19.6.1 (7) of the C99 standard.

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

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

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

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

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