void *malloc(size_t size);
申请 size 个字节的内存空间。
假如想申请一块内存,能存 n 个 int。
常见错误
int *p; p = malloc(n);
只申请了 n 个字节,但没有考略 int 本身的大小。
正确书写
p = malloc(n * sizeof(int));
void *memcpy(void *dest, const void *src, size_t n);
使用 memcpy 和 malloc 即可实现动态数组。
int *a; int size; int capacity;
使用 size 记录数组使用了多少个 int,使用 capacity 记录 a 申请了多少个 int
当 capacity 不足时使用 malloc 和 memcpy 申请新空间和复制数组
int ncap = (capacity + 1) * 2; int *t = malloc(sizeof(int) * ncap); if(t == NULL) { 错误处理 } memcpy(t, a, size * sizeof(int)); free(a); a = t; capacity = ncap;
原文:https://www.cnblogs.com/sau-autumnwind/p/14266659.html