#include <iostream> #include <string> #include <windows.h> using namespace std; //定义一种类型 typedef struct MoreAndMore { char name[66];//68 int age;//4 char *subname;//4 } mam; //创建结构体指针 mam * creatStructArr(int a) { int i = 0, j = 0;//定义遍历数 mam *arr = (mam *)malloc(3 * sizeof(mam));//分配一个大内存 //遍历输入赋值结构体内容 for (i = 0; i < 3; i++) { cout << "name:" << endl; cin >> arr[i].name;//输入name cout << "age:" << endl; cin >> arr[i].age;//输入age char *p = (char *)malloc(100 * sizeof(char));//分配一个小内存 //遍历初始化值 for (j = 0; j < 100; j++) { p[j] = 0; } cout << "subname:" << endl; cin >> *p;//输入subname arr[i].subname = p;//把内存指针挂在结构体上面 } return arr; } //遍历释放结构体内部malloc的内存 void freeStruct(mam *p,int n) { for (int i = 0; i < n; i++) { if ((p + i)->subname != NULL) { free((p + i)->subname); } } } //释放内存 void freeS(mam *p) { if (p != NULL) { free(p); } } //打印 void printStruct(mam *p, int n) { int i = 0; for (i = 0; i < 3; i++) { cout << "name:" << (p+i)->name << endl; cout << "age:" << (p + i)->age << endl; cout << "subname:" << (p + i)->subname << endl; } } void main() { /*mam xiao = { "axxa",NULL,21 }; cout << sizeof(mam) << endl;*/ int i = 0;//遍历数 int n = 3;//要自动生成的个数 mam *p = creatStructArr(n);//开始生成 返回指针 printStruct(p, n);//打印 freeStruct(p, n);//释放 p = NULL;//避免野指针 system("pause"); }