【C/C++】malloc()

<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类型的指针,如果需要该指针指向特定的类型必须进行强张类型转换。

下例:

 1 /*
 2 INPUT: NUM
 3 OUTPUT:从2开始的NUM个素数
 4 */
 5 #include<stdio.h>
 6 #include<math.h>
 7 #include<malloc.h>
 8 int isprime(long n);// if integer n is prime,return 1,else return 0.
 9 int main()
10 {
11     long *ps;
12     long n;
13     int i=0;
14     int num;
15     printf("INPUT THE NUMBER OF PRIMES YOU WANT(START FROM 2):
");
16     scanf("%d",&num);
17     ps=(long*)malloc(num*sizeof(long));// 强制类型转换
18     if(ps==NULL)
19     {
20         printf("NO ENOUGH SPACE TO STORE THESE PRIME NUMBERS:
");
21         return 0;
22     }
23     ps[i++]=2;//最小素数进组
24     n=3;//设置遍历初始值
25     while(i<num)
26     {        
27         if(isprime(n))
28             ps[i++]=n; 
29          n+=2;//跳过偶数
30     }
31         
32     //output
33     printf("
PRIME NUMBERS:
");
34     for(i=0;i<num;i++)
35         printf("%ld	",ps[i]);
36     printf("
");
37     free(ps);// 释放堆空间.
38     return 0;
39 }
40 
41 int isprime(long n)
42 {
43     int bound;
44     int i;
45     bound=(int)sqrt(n);
46     for(i=2;i<=bound;i++)
47         if(n%i==0)
48             return 0;
49     return 1;
50 }
原文地址:https://www.cnblogs.com/wxiaoli/p/5331951.html