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="{"spm":"1001.2101.3001.4259"}"></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,因此我们需要一层一层的对它进行解封。