
yoyoso的个人页面工作日志
正文


yoyoso发布于 2014/12/25 14:13
字数 589
阅读 3151

同样是后端开发,年薪50万和年薪20万的差距在哪里>>> 
strlen与sizeof返回的类型都为size_t,而size_t在32位和64位下有不同的定义:32位下typedef unsigned int size_t,64位下typedef unsigned long size_t。
如果还要用printf来打印size_t类型的函数,用%d会出现32/64下不兼容的状况size-t和unsigned int,编译器会给出waring。解决方法是使用%Zd或者%zd。%zd是C99规定的,%Zd是GNU的扩展。

关于z的解释可以在上面提到:
The length modifier
Here, "integer conversion" stands for d, i, o, u, x, or X conversion.
hh A following integer conversion corresponds to a signed char or
unsigned char argument, or a following n conversion corresponds
to a pointer to a signed char argument.
h A following integer conversion corresponds to a short int or
unsigned short int argument, or a following n conversion corre‐
sponds to a pointer to a short int argument.
l (ell) A following integer conversion corresponds to a long int
or unsigned long int argument, or a following n conversion cor‐
responds to a pointer to a long int argument, or a following c
conversion corresponds to a wint_t argument, or a following s
conversion corresponds to a pointer to wchar_t argument.
ll (ell-ell). A following integer conversion corresponds to a long
long int or unsigned long long int argument, or a following n
conversion corresponds to a pointer to a long long int argument.
L A following a, A, e, E, f, F, g, or G conversion corresponds to
a long double argument. (C99 allows %LF, but SUSv2 does not.)
q ("quad". 4.4BSD and Linux libc5 only. Don't use.) This is a
synonym for ll.
j A following integer conversion corresponds to an intmax_t or
uintmax_t argument.
z A following integer conversion corresponds to a size_t or
ssize_t argument. (Linux libc5 has Z with this meaning. Don't
use it.)
t A following integer conversion corresponds to a ptrdiff_t argu‐
ment.
当应该将size_t类型数组传参给int类型时,C语言下直接使用(int)强制转换,C++下最好是使用static_cast<int>了。

有时候会想strlen、sizeof的返回结果不会很大,有必要在64位下用unsigned long指定返回类别吗?再延伸一下思考,32位系统最多分配4G内存,一个程序可以吃4G以上的空间,这种意愿是也许的size-t和unsigned int,但针对一个程序来说是否有必要,开一个内存空间给一个指针,而这个空间就达到4G了?看看人家的说法:
size_t is guarenteed to be able to hold the size in bytes of any object you can allocate in memory. This usually tends to imply that it is the same size as a pointer, which in turn is typically the size of a CPU register.
参考:
著作权归作者所有
上一篇:ld: symbol(s) not found for architecture armv7错误
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-128906-1.html
伊拉克现在一团糟
台湾同胞户口迁移实行多样补贴和帮助
现在美国佬派出3艘驱逐舰是来干扰的