分配什么长度的内存多少个。并且初始化。
- 分配数组
int *a = calloc(8, sizeof(int));
if(a){
for (size_t i = 0; i < n; i++) {
printf("a[%zu]=%d\n", i, a[i]);
}
}
- 分配结构体
typedef struct Point {
int x;
int y;
} Point_t;
Point_t *points = calloc(3, sizeof(Point_t));
if (!points) {
perror("calloc");
return 1;
}
//赋值
points[0].x = 5;
points[0].y = 10;
for (size_t i = 0; i < n; i++) {
printf("points[%zu]=(%d, %d)\n", i, points[i].x, points[i].y);
}