strlen與sizeof返回的類型都爲size_t,而size_t在32位和64位下有不一樣的定義:32位下typedef unsigned int size_t,64位下typedef unsigned long size_t。html
若是須要用printf來打印size_t類型的變量,用%d會出現32/64下不兼容的狀況,編譯器會給出waring。解決辦法是使用%Zd或者%zd。%zd是C99規定的,%Zd是GNU的擴展。ui
關於z的解釋能夠在下面看到:
this
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>了。
.net
有時候會想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.code
參考:htm
http://blog.csdn.net/eroswang/article/details/6118224
blog
http://abloz.com/2010/12/15/sizeof-32-bit-and-64-bit-compatibility.html
內存