C语言中calloc() 与 malloc() 的区别
calloc()
calloc() 函数代表连续位置。它的工作原理类似于 malloc(),但它分配多个相同大小的内存块。
以下是 C 语言中 calloc() 的语法:
void *calloc(size_t number, size_t size);
这里:
number - 要分配的数组元素个数。
size - 以字节为单位分配的内存大小。
以下是在 C 语言中使用 calloc() 的示例:
示例
#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("
Error! memory not allocated.");
exit(0);
}
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
return 0;
}输出
Enter elements of array : 2 24 35 12 Sum : 73
在上述程序中,内存块由 calloc() 分配。如果指针变量为空,则没有内存分配。如果指针变量不为空,则用户必须输入数组的四个元素,然后计算元素的总和。
p = (int*) calloc(n, sizeof(int));
if(p == NULL) {
printf("
Error! memory not allocated.");
exit(0);
}
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}malloc()
malloc() 函数用于分配请求大小的字节,并返回指向分配内存第一个字节的指针。如果失败,则返回空指针。
以下是 C 语言中 malloc() 的语法:
pointer_name = (cast-type*) malloc(size);
这里:
pointer_name - 指针的任意名称。
cast-type - 您希望 malloc() 分配的内存转换为的数据类型。
size - 以字节为单位分配的内存大小。
以下是在 C 语言中使用 malloc() 的示例:
示例
#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("
Error! memory not allocated.");
exit(0);
}
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
return 0;
}以下是输出:
输出
Enter elements of array : 32 23 21 8 Sum : 84
在上述程序中,声明了四个变量,其中一个是存储 malloc 分配的内存的指针变量 *p。数组的元素由用户打印,并打印元素的总和。
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
printf("
Error! memory not allocated.");
exit(0);
}
printf("
Enter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("
Sum : %d", s);
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP