1、malloc函数
malloc函数是C语言中用于动态内存分配的主要函数之一。它的原型如下:
1void* malloc(size_t size);
malloc函数接受一个size_t类型的参数,表示要分配的字节数,并返回一个指向分配的内存区域的指针。如果内存分配成功,则返回非空指针;如果内存分配失败,则返回NULL。
malloc函数的示例代码:
- 1#include <stdio.h>
- 2#include <stdlib.h>
- 3
- 4int main(int argc, char *argv[]) {
- 5 int* p;
- 6 int n = 5;
- 7
- 8 // 使用malloc分配内存
- 9 p = (int*)malloc(n * sizeof(int));
- 10 if (p == NULL) {
- 11 printf("内存分配失败!\n");
- 12 return 1;
- 13 }
- 14
- 15 // 使用分配的内存
- 16 for (int i = 0; i < n; i++) {
- 17 p[i] = i + 1;
- 18 }
- 19
- 20 // 打印数组元素
- 21 for (int i = 0; i < n; i++) {
- 22 printf("%d ", p[i]);
- 23 }
- 24 printf("\n");
- 25
- 26 // 释放内存
- 27 free(p);
- 28
- 29 return 0;
- 30}
在上面的示例中,首先使用malloc函数分配了一个大小为n个int类型的内存区域,并将返回的指针赋值给p。然后,使用这块内存存储了一些数据,并打印出来。最后,使用free函数释放了这块内存。
2、calloc函数
calloc函数与malloc函数类似,也是用于动态内存分配的。它的原型如下:
1void *calloc(size_t nmemb, size_t size);
calloc函数接受两个参数:nmemb表示要分配的元素个数,size表示每个元素的大小。与malloc不同的是,calloc还会将分配的内存区域初始化为0。
calloc函数的示例代码:
- 1#include <stdio.h>
- 2#include <stdlib.h>
- 3
- 4int main(int argc, char *argv[]) {
- 5 int* p;
- 6 int n = 5;
- 7
- 8 // 使用calloc分配并初始化内存
- 9 p = (int*)calloc(n, sizeof(int));
- 10 if (p == NULL) {
- 11 printf("内存分配失败!\n");
- 12 return 1;
- 13 }
- 14
- 15 // 打印数组元素(应为0)
- 16 for (int i = 0; i < n; i++) {
- 17 printf("%d ", p[i]);
- 18 }
- 19 printf("\n");
- 20
- 21 // 释放内存
- 22 free(p);
- 23
- 24 return 0;
- 25}
在上面的示例中,使用calloc函数分配了一个大小为n个int类型的内存区域,并将返回的指针赋值给p。由于calloc会将分配的内存区域初始化为0,因此打印出来的数组元素都应该是0。最后,使用free函数释放了这块内存。
|