简体   繁体   English

尝试单独打印变量时,Printf打印错误的值,同时打印此变量和另一个变量时,Printf的打印正确的值

[英]Printf prints wrong value when trying to print the variable alone, prints the right value when printing this variable along with another variable

I have an embedded board and a camera connected to it. 我有一个嵌入式板和一个与其相连的相机。 I am trying to print the timestamp from the camera on the console output of the embedded board. 我正在尝试从相机在嵌入式开发板的控制台输出上打印时间戳。 The timestamp is accessed and loaded into a structure, and is printed using printf, as follows: 时间戳被访问并加载到结构中,并使用printf进行打印,如下所示:

This code is in a loop. 此代码处于循环中。

f.timestamp = hrt_absolute_time(); // Inbuilt function
printf("Timestamp is %u",f.timestamp);

If these lines are run, it always prints "Timestamp is 77". 如果运行了这些行,它将始终打印“ Timestamp is 77”。 If I do this instead: 如果我改为这样做:

counter = 1;
f.timestamp = hrt_absolute_time();
printf("The %d st timestamp is %u",counter,f.timestamp);

If these lines are run, it prints "The 1 st timestamp is " and the timestamp is updated every second. 如果运行了这些行,它将显示“第一个时间戳为”,并且时间戳每秒钟更新一次。 My question is, how can something so trivial cause such a huge difference? 我的问题是,琐碎的事情怎么会造成如此巨大的差异? Is it because of the stdout buffer not cleared from some old printf? 是否因为未从某些旧的printf中清除stdout缓冲区? There are no other print statements in this module. 该模块中没有其他打印语句。 Does anyone have any ideas? 有人有什么想法吗? Thanks in advance! 提前致谢!

Entire block: 整个块:

if (msg->msgid == MAVLINK_MSG_ID_OPTICAL_FLOW) {
    mavlink_optical_flow_t flow;
    mavlink_msg_optical_flow_decode(msg, &flow);

    struct optical_flow_s f;

    f.timestamp = hrt_absolute_time();
    f.flow_raw_x = flow.flow_x;
    f.flow_raw_y = flow.flow_y;
    f.flow_comp_x_m = flow.flow_comp_m_x;
    f.flow_comp_y_m = flow.flow_comp_m_y;
    f.ground_distance_m = flow.ground_distance;
    f.quality = flow.quality;
    f.sensor_id = flow.sensor_id;

    printf("Timestamp is %u",f.timestamp);
            //OTHER CODE FOLLOWS

According to information in the comments, f.timestamp is of type uint64_t . 根据注释中的信息, f.timestamp的类型为uint64_t

Unless uint64_t is the same type as unsigned int , the behavior of 除非uint64_tunsigned int类型相同,否则其行为

printf(" timestamp is %u", f.timestamp);

is undefined. 未定义。

The header <inttypes.h> defines format macros for a number of integer types, but I find it easier to cast to a known type: 标头<inttypes.h>定义了许多整数类型的格式宏,但我发现将其转换为已知类型更容易:

printf(" timestamp is %ju", (uintmax_t)f.timestamp);

or 要么

printf(" timestamp is %llu", (unsigned long long)f.timestamp);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM