如何在 C/C++ 中使用 malloc() 和 free()?
malloc()
该函数 malloc() 用于分配所需大小的字节并返回一个指向已分配内存第一个字节的指针。如果它失败,则返回空指针。
以下是 malloc() 在 C 语言中的语法,
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("\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
free()
该函数 free() 用于释放由 malloc() 分配的内存。它不会更改该指针的值,这意味着它仍然指向同一内存位置。
以下是 free() 在 C 语言中的语法,
void free(void *pointer_name);
其中,
pointer_name − 赋予该指针的任意名称。
以下是在 C 语言中 free() 的一个示例,
示例
#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);
free(p);
return 0;
}输出
以下是输出
Enter elements of array : 32 23 21 28 Sum : 104
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP