在这个问题,有人建议意见,我应该不会投的结果malloc,即
int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
而不是:
int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
为什么会这样呢?
众所周知,它与初始化分配的内存calloc不同malloc.使用时calloc,内存设置为零.使用时malloc,内存不会被清除.
所以在日常工作中,我认为calloc是malloc+ memset.顺便说一下,为了好玩,我为基准编写了以下代码.
结果令人困惑.
代码1:
#include<stdio.h>
#include<stdlib.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)calloc(1,BLOCK_SIZE);
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
代码1的输出:
time ./a.out
**real 0m0.287s**
user 0m0.095s
sys 0m0.192s
Run Code Online (Sandbox Code Playgroud)
代码2:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BLOCK_SIZE 1024*1024*256
int main()
{
int i=0;
char *buf[10];
while(i<10)
{
buf[i] = (char*)malloc(BLOCK_SIZE);
memset(buf[i],'\0',BLOCK_SIZE);
i++;
}
}
Run Code Online (Sandbox Code Playgroud)
代码2的输出:
time ./a.out
**real 0m2.693s**
user 0m0.973s
sys 0m1.721s
Run Code Online (Sandbox Code Playgroud)
更换 …
我不太明白应该如何在C的源文件和头文件中分离.我经常看到许多项目有两组具有相同名称的文件(没有表示源文件和头文件的扩展名).
到目前为止,由于缺乏理解,当我编写库时,我已将所有类和类方法代码放入一个文件中,并且选择文件扩展名时犹豫不决.
什么应该在标题中以及源文件中应该包含哪些内容?我该如何实现这种分离?