设为首页 加入收藏

TOP

动态开内存(malloc与calloc)
2019-08-04 00:07:26 】 浏览:64
Tags:动态 内存 malloc calloc

malloc与calloc

1.函数原型

   #include<stdlib.h>

   void *malloc(unsigned int size);     //申请size字节的内存

   void *calloc(unsigned int num, unsigned size);    //申请num*size字节的内存

2.函数的返回值为void*类型,使用时需强制转换为所需要的类型;

   如果内存申请失败,则返回NULL,所以使用申请到的内存时需要先进行判断。

   如:char* p = (char*)malloc(6 * sizeof(char));

3.申请的内存位于堆中,不再需要使用时,需调用free函数释放

   void free(void *p);

注意:

1.void *与NULL

  int *p=NULL;

  void *p;

2.malloc与数组的比较:

(1)传给malloc函数的实参可以是一个表达式,从而可以“动态”申请一块内存;

(2)使用malloc函数申请的内存可以从函数中返回;而使用数组则不可以(存放在栈中,当函数返回时,内存已经被释放),示例代码如下:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 int main()
 4 {
 5     char* func1();
 6     char* func2();
 7     char* pf1;
 8     char* pf2;
 9     pf1 = func1();
10     pf2 = func2();
11     printf("%s\n", pf1);    //输出f1
12     printf("%s\n", pf2);    //输出乱码,错误信息-返回局部变量的地址
13 }
14 
15 char* func1()
16 {
17     char* p = (char*)malloc(3 * sizeof(char));
18     if (p)
19     {
20         p[0] = 'f';
21         p[1] = '1';
22         p[2] = '\0';
23         return p;
24     }
25     return NULL;
26 }
27 
28 char* func2()
29 {
30     char p[3] = "f2";
31     return p;
32 }

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C语言中,static关键字作用 下一篇回调函数的作用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目