【发布时间】:2011-12-15 01:32:44
【问题描述】:
代码:
#include "stdafx.h"
#include "stdio.h"
#include "math.h"
#include "stdlib.h"
#include "time.h"
int main()
{
time_t start, end;
time (&start);
int i;
double dif;
/*int serie[100000];*/
/* int *serie = malloc( sizeof(int) );
for (i = 0; i <= 100000; i++) {
*serie(i)=rand();
printf("%d \n", serie[i]);
}
*/
time (&end);
dif = difftime (end, start);
printf ("Time of execution is: %f\n", dif );
getchar();
return 0;
}
简介:(不用看)
大约 3 年前,我对 C++ 有所了解。我已决定 学习 C 以创建“快速”子集和算法。这是一个 学习 C 的简单程序。问题是创建随机数和 时间吧。当我编译为默认或 C++ 和 Visual Studio,但我决定用 C 来做 我想创建一个动态数组。
C中好像没有new,我们只好用malloc,
但是要编译malloc,我认为它必须用C编译。在C++中,
它给了我这个错误:
cannot convert from 'void *' to 'int *'
不管怎样,碰巧我决定用 C 编写,所以看起来合乎逻辑
用 C 编译。我选择了time 函数来测量程序,
我比clock 更喜欢它,因为我不知道有多少个处理器
正在工作。
问题:
上面带有 cmets 的代码在 C++ 中可以完美编译,但在 C 中它不能编译。 具体来说,这一行:
time (&start);
给我这个错误:
syntax error : missing ';' before 'type'
我只想计算开始时间和结束时间,然后
正如我在 C++ 中成功完成的那样,用 difftime 减去它们。
【问题讨论】:
-
使用
#include <xxx.h>而不是#include "xxx.h" -
stdafx.h是不必要的;它是 Microsoft 特定的,您没有使用它。可以从C++调用malloc(),但是转换规则不同;它返回一个void*结果,它可以隐式转换为C 中的目标类型,但不能在C++ 中。但是无论如何你都应该在 C++ 中使用new和delete——或者更好的是,一些容器类。是的,当然如果你正在编写 C 代码,你应该使用 C 编译器,如果你正在编写 C++ 代码,你应该使用 C++ 编译器。它们是不同(但密切相关)的语言。