【问题标题】:timeval not returning expecting resultstimeval 未返回预期结果
【发布时间】:2011-08-09 21:55:58
【问题描述】:

我有一些代码如下所示:

#include <stdio.h>
#include <sys/time.h>

typedef struct{
     struct timeval timestamp;
}teststruct;

class TestClass {
     public:
       TestClass();
       void dosomething(int, int);
};

TestClass::TestClass(){
}

void
TestClass::dosomething(int num, int numb) {
}

int main(void){
     TestClass *testclass = new TestClass();
     teststruct test;
     gettimeofday(&test.timestamp, NULL);
     printf("%llu \n", test.timestamp.tv_sec);
     testclass->dosomething(1,1);
     printf("%llu \n", test.timestamp.tv_sec);
}

这段代码的输出是:

13825459612132795564 做一点事 5598307500

但我不知道为什么第一个数字搞砸了。此外,为了使数字彼此不同,课程调用是完全必要的。

【问题讨论】:

  • 为什么将 timeval 变量包装到 typedef 结构中?

标签: c++ timeval time.h


【解决方案1】:

我收到warning: format ‘%llu’ expects type ‘long long unsigned int’, but argument 2 has type ‘__time_t’。应该是提示。将编译器的警告级别提高到合理的水平。

当你使用正确的输入类型时它works。否则,您正在调用 UB,读取不属于您的内存;像这样的错误可能会产生有趣的结果,这些结果会根据您通常不会期望产生影响的因素而产生不同的行为,因为您的内存内容会发生变化。

【讨论】:

    【解决方案2】:

    如果您将%llu 更改为%lu,似乎可以工作。

    http://codepad.org/YGubabLR

    【讨论】:

      猜你喜欢
      • 2010-09-22
      • 2021-05-17
      • 2018-02-19
      • 2018-03-23
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多