该功能calloc()代表连续位置。它的工作方式类似于,malloc()但是它分配了多个相同大小的内存块。
这是calloc()C语言的语法,
void *calloc(size_t number, size_t size);
这里,
号将被分配数组的元件的数量- 。
大小-以字节为单位分配的内存大小。
这是calloc()C语言的示例,
#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) calloc(n, sizeof(int));
   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");
   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   return 0;
}输出结果
Enter elements of array : 2 24 35 12 Sum : 73
在上面的程序中,内存块由分配calloc()。如果指针变量为null,则没有内存分配。如果指针变量不为空,则用户必须输入数组的四个元素,然后计算元素之和。
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
   printf("\nError! memory not allocated.");
   exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
   scanf("%d", p + i);
   s += *(p + i);
}该函数malloc()用于分配请求的字节大小,并返回指向已分配内存的第一个字节的指针。如果失败,则返回空指针。
这是malloc()C语言的语法,
pointer_name = (cast-type*) malloc(size);
这里,
pointer_name-给指针的任何名称。
cast- type-您要通过强制转换分配的内存的数据类型malloc()。
大小-以字节为单位分配的内存大小。
这是malloc()C语言的示例,
#include <stdio.h>
#include <stdlib.h>
int main() {
   int n = 4, i, *p, s = 0;
   p = (int*) malloc(n * sizeof(int));
   if(p == NULL) {
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");
   for(i = 0; i < n; ++i) {
      scanf("%d", p + i);
      s += *(p + i);
   }
   printf("\nSum : %d", s);
   return 0;
}这是输出,
输出结果
Enter elements of array : 32 23 21 8 Sum : 84
在上面的程序中,声明了四个变量,其中之一是指针变量* p,它存储由malloc分配的内存。数组的元素由用户打印,元素的总和打印。
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
   printf("\nError! memory not allocated.");
   exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
   scanf("%d", p + i);
   s += *(p + i);
}
printf("\nSum : %d", s);