Android 底层开发 C语言基础 - 内存管理篇(1)
Clion 环境
main.c
#include<stdio.h>
#include<stdlib.h>
/**
* calloc:会初始化内存+元素个数+单个内存尺寸
* realloc:不会初始化内存+原始指针+拓展后的总体大小
*/
int main() {
printf("=== calloc realloc 探索 ===");
//创建大小sizeof(int) * 25 的块内存,返回首元素地址
int *p = (int *) calloc(25, sizeof(int));
printf("指针地址:%p , 首元素地址: %p \n",p,&p[0]);
//初始化内存存储的东西
for (int i = 0; i < 25; ++i) {
p[i] = i;
}
//内存扩容,原来的基础上又加上 sizeof(int) * 25
p = (int *) realloc(p, sizeof(int) * 50);
for (int i = 25; i < 50; ++i) {
p[i] = i;
}
for (int j = 0; j < 50; ++j) {
printf("%d ",p[j]);
}
return 0;
}
=== calloc realloc 探索 ===
指针地址:0x7f9f61c02a10 , 首元素地址: 0x7f9f61c02a10
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
Process finished with exit code 0