【C/C++】malloc()
2016-03-29 10:17
323 查看
<math.h>文件中对malloc()函数原型:
_CRTIMP void * __cdecl malloc(size_t);
MSDN中对malloc()的解释:
即:malloc总是返回void类型的指针,如果需要该指针指向特定的类型必须进行强张类型转换。
下例:
_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=0; 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 0; } ps[i++]=2;//最小素数进组 n=3;//设置遍历初始值 while(i<num) { if(isprime(n)) ps[i++]=n; n+=2;//跳过偶数 } //output printf("\nPRIME NUMBERS:\n"); for(i=0;i<num;i++) printf("%ld\t",ps[i]); printf("\n"); free(ps);// 释放堆空间. return 0; } int isprime(long n) { int bound; int i; bound=(int)sqrt(n); for(i=2;i<=bound;i++) if(n%i==0) return 0; return 1; }
相关文章推荐
- c++适配器
- 自己实验C++
- C语言(浮点精度)
- C++ ofstream和ifstream详细用法
- this指针 C++
- configure: error: C++ preprocessor "/lib/cpp" fails sanity check
- C++与Java的输入问题
- C++ # 条件编译的理解
- c的详细学习(1)C语言概述
- 2016年,C语言该怎样写
- C++中FTP上传功能(仅用系统库)
- C++学习笔记
- C语言实现整数四则运算表达式的计算
- c++上机作业测试体重是否标准并输出相关提示
- 2D武侠游戏《剑侠世界》网游单机 搭建教程说明
- C++ 深入new
- VC++ 打印类
- C++ 元编程的魔法
- C++-内存管理(整理笔记)
- 2015年蓝桥杯省赛A组C/C++:奇妙的数字