1.只有一个malloc的情况
//柔性数组的使用
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
struct s
{int i;int a[];
};
int main()
{struct s* ps = (struct s*)malloc(sizeof(struct s) + 20 * sizeof(int));if (ps == NULL){perror("malloc");return 1;}//使用这块空间ps->i = 100;int j = 0;for (j = 0; j < 20; j++){ps->a[j] = j + 1;}//调整ps指向空间的大小struct s* str = (struct s*)realloc(ps, sizeof(struct s) + 40 * sizeof(int));if (str != NULL){ps = str;str = NULL;}//使用空间后面开辟的40个字节,打印出来for (j = 0; j < 40; j++){ps->a[j] = j + 1;}for (j = 0; j < 40; j++){if (j % 10 == 0){printf("\n");}printf("%d ", ps->a[j]);}//释放空间free(ps);ps = NULL;return 0;
}
2.有两个malloc的情况
#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
struct s
{int i;int* a;
};
int main()
{struct s* ps = (struct s*)malloc(sizeof(struct s));if (ps == NULL){perror("malloc");return 1;}int* tmp = (int*)malloc(20 * sizeof(int));if (tmp != NULL){ps->a = tmp;}else{perror("malloc");return 1;}ps->i = 100;int j = 0;for (j = 0; j < 20; j++){ps->a[j] = j + 1;}//调整空间tmp = (int *)realloc(ps->a, 40 * sizeof(int));if (tmp != NULL){ps->a = tmp;}else{perror("realloc");return 1;}for (j = 0; j < 40; j++){ps->a[j] = j + 1;}for (j = 0; j < 40; j++){printf("%d ",ps->a[j]);}free(ps->a);ps->a = NULL;free(ps);ps = NULL;return 0;
}
输出结果:
对于一个malloc和两个malloc相对比,很明显,一个malloc会相对简单,所以一般我们都会使用一个malloc,但是也可以学习一下两个malloc的使用方法。