如何打印int的长度用C? [英] How do I print the size of int in C?

查看:231
本文介绍了如何打印int的长度用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编译下面的RHEL 5.6,64位,和我不断收到警告

I am trying to compile the below on RHEL 5.6 , 64 bit, and i keep getting a warning

var.c:7:警告:格式%d,可预期
  类型'诠释',但参数2的类型
  长unsigned int类型'。

"var.c:7: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long unsigned int’"

下面是我的code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned int n =10;
    printf("The size of integer is %d\n", sizeof(n));
}

如果我为N的宣言更改为以下不要紧

It does not matter if i change the declaration for "n" to following


  1. 符号int N = 10;

  2. INT N = 10;

所有我想要做的就是打印整数的大小我的机器上,并没有真正寻找到limits.h中。

All i want to do is print the size of integer on my machine, without really looking into limits.h.

推荐答案

sizeof运算函数也返回size_t类型。尝试使用%祖作为转换符代替%d个。

The sizeof function returns a size_t type. Try using %zu as the conversion specifier instead of %d.

printf("The size of integer is %zu\n", sizeof(n));

要澄清一下,使用%祖如果你的编译器支持C99;否则,或者如果你想最大的可移植性,以打印为size_t价值的最佳方法是将其转换
为unsigned long和使用%lu个。

To clarify, use %zu if your compiler supports C99; otherwise, or if you want maximum portability, the best way to print a size_t value is to convert it to unsigned long and use %lu.

printf("The size of integer is %lu\n", (unsigned long)sizeof(n));

这样做的原因是,为size_t由标准保证是一个无符号类型;但是标准没有规定,它必须是任何特定的大小,(只是大到足以重新present任何物体的大小)。事实上,如果无符号长不能重新present为您的环境中最大的对象,你甚至可能需要使用一个unsigned long长投和%LLU符。

The reason for this is that the size_t is guaranteed by the standard to be an unsigned type; however the standard does not specify that it must be of any particular size, (just large enough to represent the size of any object). In fact, if unsigned long cannot represent the largest object for your environment, you might even need to use an unsigned long long cast and %llu specifier.

在C99加入的Z长度修改,以提供一种方法来指定正在打印的值是为size_t类型的大小。通过使用%祖要表示正在打印的价值为size_t大小的无符号值。

In C99 the z length modifier was added to provide a way to specify that the value being printed is the size of a size_t type. By using %zu you are indicating the value being printed is an unsigned value of size_t size.

这是在哪里,好像你不应该去想的事情之一,但你做的。

This is one of those things where it seems like you shouldn't have to think about it, but you do.

延伸阅读:

  • printf and size_t
  • portable way to print a size_t instance
  • assuming size_t is unsigned long

这篇关于如何打印int的长度用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆