p { margin-bottom: 0.21cm; }
Dynamic Memory Allocation With calloc() and malloc()
C 语言在标准库中提供calloc() 和malloc() 了,它们的函数声明存放在stdlib.h 中。Calloc 表示“连续分配(contiguous allocation)”,malloc 表示“内存分配“
程序员使用calloc() 和malloc() 来动态地创造数组,结构体和共用体。以下是一个典型的展示calloc() 动态地为一个数组分配空间的例子。
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int a; /* to be used as an array */
int n; /* the size of the array */
…... /* get n from somewhere, perhaps interactively from the
user*/
a=calloc(n,sizeof(int)); /* get space for a*/
…... /* use a as an array */
calloc() 有两个size_t 类型的成员,在ANSI C 中,size_t 是一个无符号整数类型。典型地,一个typedef( 类型定义) 在stdlib.h 被用来使得size_t 与unsigned int 类型相等。一个函数调用这种形式:calloc(n, el_size) 在内存一段连续的空间中分配有n 个元素(element) 的数组,每个元素占有类型为el_size 的空间。空间中所有位被初始化为0 。如果申请是成功的,一个void * 类型的指向数组一段内存的指针被返回。否则返回NULL 。注意sizeof 操作的使用使得代码能够适合于2 或4 字节的机器。
a=calloc(n,sizeof(int));
和
a=malloc(n*sizeof(int));
基本等价
区别是后者并不将数组初始化为0 。在大型程序中malloc 可以提供更短的时间。
calloc 和malloc 动态分配的空间并不会随离开函数自动返回系统。程序员必须要显式调用free() 放回这部分空间。一个申明的形式:
free(ptr)
这个申明使得ptr 所指向的内存空间被释放。如果ptr 是NULL, 函数是无效的,如果ptr 不是NULL, 它一定是之前由alloc(),malloc,realloc() 创造的空间所指向的指针并且还没有被free() 和realloc() 销毁。否则这项申请是错误的。这个错误的效果是由系统决定的。
demo:
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
void fill_array(int *a,int n);
int sum_array(int *a,int n);
void wrt_array(int *a,int n);
int main()
{
int *a,n;
srand(time(NULL)); /* seed the random number generator */
printf("/n%s/n",
"This program does the following repeatedly:/n"
"/n"
" 1 create space for an array of size n/n"
" 2 fill the array with randomly distributed digits/n"
" 3 print the array and the sum of its element/n"
" 4 release the space/n");
for( ; ; ) {
printf("Input n: ");
if(scanf("%d",&n)!=1||n<1)
break;
putchar('/n');
a=calloc(n,sizeof(int)); /* allocate space for a[] */
fill_array(a,n);
wrt_array(a,n);
printf("sum=%d/n/n",sum_array(a,n));
free(a);
}
printf("/nBye!/n/n");
return 0;
}
void fill_array(int *a, int n)
{
int i;
for(i=0;i<n;++i)
a[i]=rand()%19 - 9;
}
int sum_array(int *a,int n)
{
int i,sum=0;
for(i=0;i<n;++i)
sum+=a[i];
return sum;
}
void wrt_array(int *a, int n)
{
int i;
printf("a=[");
for (i=0;i<n;++i)
printf("%d%s", a[i],((i<n-1)?",":"]/n"));
}
附:C语言强制类型转换
char b='a';
a=(int)b;
/*强制将b转换为int型传给a*/
类似地
int *p;
p=malloc(sizeof(int));
/*此处默认分配int空间后返回为int *类型*/
p=(int*)malloc(2*sizeof(char));
/*此处强制转换分配int空间*/