C-动态内存分配-calloc函数
时间:2020-02-23 14:31:53 来源:igfitidea点击:
在本教程中,我们将学习用C编程语言动态分配内存的calloc函数。
calloc函数
我们使用calloc函数在运行时为派生的数据类型(如数组和结构)分配内存。
使用calloc函数,我们可以分配多个具有相同大小的内存块,并且所有字节都将设置为0。
这与上一教程中用来分配单个内存空间的malloc函数不同。
Calloc语法
以下是calloc函数的语法,用于动态分配内存。
ptr = (cast_type *) calloc (n, element_size);
其中," ptr"是" cast_type"类型的指针。
n是连续空间的总块,每个空间的大小为element_size,将使用calloc函数分配。
Calloc示例
在下面的示例中,我们为3个学生结构变量分配内存空间。
//student structure
struct student {
char id[10];
char firstname[64];
char lastname[64];
int score;
};
//new type
typedef struct student candidate;
//student structure pointer
candidate *sptr;
//variables
int no_of_students = 3;
//allocate memory blocks
sptr = (candidate *) calloc (no_of_students, sizeof(candidate));
在上面的代码中,我们分配了3个存储空间块,每个块的大小为候选结构,即140个字节。
| 成员 | 数据类型 | 大小 |
|---|---|---|
| id | char | 10个字节 |
| firstname | char | 64字节 |
| lastname | char | 64字节 |
| score | int | 2个字节 |
用C语言编写一个程序,使用calloc函数为结构动态分配内存
#include <stdio.h>
#include <stdlib.h>
int main(void) {
//student structure
struct student {
char id[10];
char firstname[64];
char lastname[64];
int score;
};
//new type
typedef struct student candidate;
//student structure pointer
candidate *sptr;
candidate *tmp;
//variables
int no_of_students = 3;
int i;
//allocate memory blocks
sptr = (candidate *) calloc (no_of_students, sizeof(candidate));
//get student details
for(i = 0, tmp = sptr; i < no_of_students; i++, tmp++) {
printf("Enter detail of student #%d\n", (i+1));
printf("ID: ");
scanf("%s", tmp->id);
printf("First Name: ");
scanf("%s", tmp->firstname);
printf("Last Name: ");
scanf("%s", tmp->lastname);
printf("Score: ");
scanf("%d", &tmp->score);
}
//display student details
printf("\n\nFollowing are the student details:\n\n");
for(i = 0, tmp = sptr; i < no_of_students; i++, tmp++) {
printf("Detail of student #%d\n", (i+1));
printf("ID: %s\n", tmp->id);
printf("First Name: %s\n", tmp->firstname);
printf("Last Name: %s\n", tmp->lastname);
printf("Score: %d\n", tmp->score);
}
//free memory location
free(sptr);
return 0;
}
Enter detail of student #1 ID: s01 First Name: Last Name: Score: 8 Enter detail of student #2 ID: s02 First Name: Jane Last Name: Doe Score: 9 Enter detail of student #3 ID: s03 First Name: John Last Name: Doe Score: 7 Following are the student details: Detail of student #1 ID: s01 First Name: Last Name: Score: 8 Detail of student #2 ID: s02 First Name: Jane Last Name: Doe Score: 9 Detail of student #3 ID: s03 First Name: John Last Name: Doe Score: 7
我们可以如下表示分配的内存。
因此,分别为三个大小为140字节的结构分配了从地址1000到1139、2000到2139和3000到3139的存储位置。
sptr结构指针指向这些存储位置。
我们正在使用一个临时的" tmp"结构指针来访问这些分配的内存块。

