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下不兼容的情况,编译器会给出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以上的空间,这种需求是可能的,但对于一个程序来说是否有必要,开一个内存空间给一个指针,而这个空间就超过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.
参考:
http://blog.csdn.net/eroswang/article/details/6118224
http://abloz.com/2010/12/15/sizeof-32-bit-and-64-bit-compatibility.html
http://www.oschina.net/question/249672_117514