您的位置:首页 > 编程语言 > C语言/C++

【C/C++】malloc()

2016-03-29 10:17 323 查看
<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=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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: