1. 给一个整数分配内存:
#include2. 给 3 个整数分配内存:#include int main(void){ int *p = NULL;// p = malloc(sizeof(int)); /* 应该像下一句同时类型转换, 不然在 C++ 里面不行 */ p = (int *)malloc(sizeof(int)); *p = 100; printf("%d\n", *p); free(p); getchar(); return 0;}
#include3. 像数组一样使用:#include int main(void){ int *p = NULL; p = (int *)malloc(sizeof(int)*3); *p = 111; *(p+1) = 222; *(p+2) = 333; printf("%d,%d,%d\n", *p, *(p+1), *(p+2)); free(p); getchar(); return 0;}
#include4. calloc 会同时初始化内存, malloc 则不会, 不初始化应该更快些:#include int main(void){ int *p = (int *)malloc(sizeof(int)*3); p[0] = 111; p[1] = 222; p[2] = 333; printf("%d, %d, %d\n", p[0], p[1], p[2]); free(p); getchar(); return 0;}
#include5. realloc:#include int main(void){ const int num = 10; // calloc 和 malloc 参数也有点区别 long *p1 = (long *)calloc(num, sizeof(long)); /* 会初始化 */ long *p2 = (long *)malloc(num * sizeof(long)); /* 不会初始化 */ int i; for (i = 0; i < num; i++) { printf("%d, %d\n", p1[i], p2[i]); } free(p1); free(p2); getchar(); return 0;}
#include6. 判断内存是否分配成功:#include int main(void){ int num = 10; int i; long *p = (long *)malloc(num * sizeof(long)); printf("内存地址: %p\n~~~~~~~~\n", p); for (i = 0; i < num; i++) p[i] = i+1; for (i = 0; i < num; i++) printf("%d\n", p[i]); printf("------------------\n"); num = 4; p = (long *)realloc(p, num*sizeof(long)); printf("内存地址: %p\n~~~~~~~~\n", p); for (i = 0; i < num; i++) printf("%d\n", p[i]); printf("------------------\n"); num = 20; p = (long *)realloc(p, num*sizeof(long)); printf("内存地址: %p\n~~~~~~~~\n", p); for (i = 0; i < num; i++) printf("%d\n", p[i]); free(p); getchar(); return 0;}
#include#include int main(void){ int *p = (int *)malloc(100); if (p != NULL) printf("分配成功!\n"); if (p) printf("分配成功!\n"); if (p == NULL) printf("内存不足!\n"); if (!p) printf("内存不足!\n"); free(p); getchar(); return 0;}