<math.h>文件中对malloc()函数原型:

_CRTIMP void *  __cdecl malloc(size_t);

MSDN中对malloc()的解释:

malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available.
To return a pointer to a type other than void, use a type cast on the return value.
  The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object.
If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item.
Always check the return from malloc, even if the amount of memory requested is small.

即:malloc总是返回void类型的指针,如果需要该指针指向特定的类型必须进行强张类型转换。

下例:

 /*
INPUT: NUM
OUTPUT:从2开始的NUM个素数
*/
#include<stdio.h>
#include<math.h>
#include<malloc.h>
int isprime(long n);// if integer n is prime,return 1,else return 0.
int main()
{
long *ps;
long n;
int i=;
int num;
printf("INPUT THE NUMBER OF PRIMES YOU WANT(START FROM 2):\n");
scanf("%d",&num);
ps=(long*)malloc(num*sizeof(long));// 强制类型转换
if(ps==NULL)
{
printf("NO ENOUGH SPACE TO STORE THESE PRIME NUMBERS:\n");
return ;
}
ps[i++]=;//最小素数进组
n=;//设置遍历初始值
while(i<num)
{
if(isprime(n))
ps[i++]=n;
n+=;//跳过偶数
} //output
printf("\nPRIME NUMBERS:\n");
for(i=;i<num;i++)
printf("%ld\t",ps[i]);
printf("\n");
free(ps);// 释放堆空间.
return ;
} int isprime(long n)
{
int bound;
int i;
bound=(int)sqrt(n);
for(i=;i<=bound;i++)
if(n%i==)
return ;
return ;
}

最新文章

  1. 【OpenGL】VAO与VBO
  2. mvc通过ActionFilterAttribute做登录检查
  3. Objective-c 代理模式(delegate)
  4. eclispe使用外部tomcat总结
  5. linux中执行命令权限不够怎样处理
  6. 取出一个int的每一位,用算法
  7. 【转】关于 hashCode() 你需要了解的 3 件事
  8. C++ 哈希表 (hashtable) 用于保存简单的数据,及数据查找,数据删除
  9. MEF初体验之四:Imports声明
  10. NSIS 自定义页面制作关闭功能
  11. DIV+CSS中的滤镜和模糊
  12. ELK搭建&lt;三&gt;:安装Kibana
  13. day13笔记
  14. Eclipse中Project的属性Deployment Assembly(部署程序集)消失了,不存在了,去哪儿了
  15. centos下安装djangobb
  16. 《剑指offer》第五十九题(滑动窗口的最大值)
  17. shlve 模块
  18. MongoDB分布式集群搭建
  19. cnn公式推导
  20. 微信小程序(wx:for)遍历对象

热门文章

  1. Swagger学习和实践
  2. Raid分类说明 (from mongodb权威指南)
  3. tcp ip协议笔记(1)——简单介绍
  4. Odoo 养猪
  5. OS: 读者写者问题(写者优先+LINUX+多线程+互斥量+代码)(转)
  6. OA权限树搭建 代码
  7. c# vitural
  8. Python生成8位随机字符串的一些方法
  9. 移动端,多屏幕尺寸高清屏retina屏适配的解决方案
  10. .Net Core表单验证