malloc详细

https://blog.csdn.net/abc882715/article/details/78438508

malloc个人认识:
malloc是一个函数,这个函数主要用于动态分配内存。
在我们运用过程中,数组虽然与可以用于开辟空间,但是相对于malloc这个函数,malloc的开辟的空间,可以在你用完内存后,迅速让计算机清楚掉。

malloc用法:
指针名=(数据类型)malloc(长度),(数据类型)表示指针.
举例1:int* buffer = (int*)malloc(8 * sizeof(int));
这行代码是说,malloc开辟了一个int类型,8个int大小的空间,并且指针buffer指向这个malloc所开辟的空间。

举例2:int** buffer = (int**)malloc(8 * sizeof(int*));
这行代码则是在说,malloc开辟了一个int**类型,8个int*大小的空间,并且二维指针指向这个malloc所开辟的空间。

那么举例1与举例2有什么区别呢?这里写图片描述

举例1
如上图所示:
指针buffer指向这个malloc开创的空间,而malloc的首地址便是buffer的首地址,malloc则是如图中所示,开创8个int类型的空间。
这里写图片描述
举例2
如上图所示:
二维指针buffer 所指的对象其实是一个集合,而这个集合里面装的是buffer1,buffer2,buffer3,而buffer1,buffer2,buffer3则是分别指向malloc的指针。

举例3:
运用malloc开辟一个8*8的int类型的空间,并对其随机赋值。

int i = 0, k = 0, j = 0;
    int** buffer = (int**)malloc(8 * sizeof(int*));
//定义**buffer指向malloc,而malloc开辟了8个int类型空间;
    for (i = 0; i < 8; i++)
    {
        buffer[i] = (int*)malloc(8 * sizeof(int));
//buffer集合下的指针buffer,让malloc开辟了8个int类型空间。ps:因为只有int类型,才能对buffer赋值
        for (k = 0; k < 8; k++)
        {
        buffer[i][k] = rand() % <span class="hljs-number">100</span> + <span class="hljs-number">1</span>;
    <span class="hljs-comment">//赋值</span>
    }

}<div class="hljs-button {2}" data-title="复制" data-report-click="{&quot;spm&quot;:&quot;1001.2101.3001.4259&quot;}"></div></code><ul class="pre-numbering" style=""><li style="color: rgb(153, 153, 153);">1</li><li style="color: rgb(153, 153, 153);">2</li><li style="color: rgb(153, 153, 153);">3</li><li style="color: rgb(153, 153, 153);">4</li><li style="color: rgb(153, 153, 153);">5</li><li style="color: rgb(153, 153, 153);">6</li><li style="color: rgb(153, 153, 153);">7</li><li style="color: rgb(153, 153, 153);">8</li><li style="color: rgb(153, 153, 153);">9</li><li style="color: rgb(153, 153, 153);">10</li><li style="color: rgb(153, 153, 153);">11</li><li style="color: rgb(153, 153, 153);">12</li><li style="color: rgb(153, 153, 153);">13</li><li style="color: rgb(153, 153, 153);">14</li><li style="color: rgb(153, 153, 153);">15</li></ul></pre> 

值得注意的是,因为** buffer是二维指针,并且指向malloc,因此我们需要一层一层的对它进行解封。

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值