现在的位置: 首页 > 综合 > 正文

24、printf跨平台,数据类型与输出类型要匹配

2011年01月31日 ⁄ 综合 ⁄ 共 1002字 ⁄ 字号 评论关闭

1、使用printf应当说是类型不安全的。所以才引入了C++的流输入输出。

比如:

#include "stdint.h"

#include "iostream"

using namespace std;

int main()

{

    int64_t a = 1;

    int b = 2;

    uint32_t uin = 1;

    printf("%p %p\n", &a, &b);

    printf("%llu\n", uin);

    cout << a << " "<< b << endl;

    printf("%d %d\n", a, b);

    return 0;

}

输出是:

0xbfd831e0 0xbfd831dc

13823853877176303617  //error

1 2

1 0  //error

可以看到,uint32_t类型,我们用lld时,出现了错误,因为printf是根据类型,从起始地址偏移类型个字节进行读取数据。

使用C++中的流便不会出现这个问题。在跨平台中,应当引起注意。

2、类型与字节数【3

%ld:long int, 32位平台4 bytes

%lld: long long int, 32位平台8 bytes

%lf:double

**************

typedef signed char       int8_t

typedef short int         int16_t;

typedef int             int32_t;

# if __WORDSIZE == 64

typedef long int         int64_t;

# else

__extension__

typedef long long int     int64_t;

#endif

参考:

1http://www.vimer.cn/2011/08/printf-%E5%B0%8F%E4%BB%A3%E7%A0%81%EF%BC%8C%E5%A4%A7%E9%97%AE%E9%A2%98.html

2http://www.cppblog.com/Solstice/archive/2010/04/06/111788.aspx

3】 类型与字节数

http://blog.sina.com.cn/s/blog_4b9eab320100sdex.html

4printf实现的探究

http://www.cnblogs.com/hnrainll/archive/2011/08/05/2128496.html

【上篇】
【下篇】

抱歉!评论已关闭.