1. 程式人生 > >結構體中包含二級指標案例

結構體中包含二級指標案例

給出如下結構體,要求全部在堆區開闢空間。有多個老師,每個老師有多個學生。

typedef struct
{
	char *name;//老師
	int stu_num;//學生數
	char **stu_arr;//學生名字
}TEACHER;

需要注意以下問題:

  1. 此問題使用雙層迴圈即可解決。
  2. 外層迴圈處理這三個成員變數:給name開闢空間;給stu_num賦值;給stu_arr開闢5個連續的儲存一級地址地char**型別的空間。即給成員變數賦值。
  3. 在內層迴圈中使用stu_arr5個char*型別的空間開闢,每個均開闢5個char*型別的空間,再給他們賦值。當然,這個過程(內層迴圈)要執行25次。即給二級地址中引用的一級地址開闢空間並賦值。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{
	char *name;
	int stu_num;
	char **stu_arr;
}TEACHER;

int main(int argc, char *argv[])
{
	TEACHER **teachers = (TEACHER **)calloc(5, sizeof(TEACHER));
	for (int i = 0; i < 5; i++)
	{
		//*name
		teachers[i] = (TEACHER*)calloc(1, sizeof(TEACHER));
		teachers[i]->name = (char *)calloc(32, sizeof(char));
		strcpy(teachers[i]->name, "lao_shi");
		printf("%s\n", teachers[i]->name);
		
		//stu_num
		teachers[i]->stu_num = 3;
		printf("%d\n", teachers[i]->stu_num);
		
		//**stu_arr 
		teachers[i]->stu_arr = (char **)calloc(5, sizeof(char *));
		printf("%p\n", teachers[i]->stu_arr);
		
		for (int j = 0; j < 5; j++)
		{
			//*stu_arr
			teachers[i]->stu_arr[j] = (char *)calloc(teachers[i]->stu_num, 128 * sizeof(char));
			strcpy(teachers[i]->stu_arr[j], "xiao_ming");
			printf("%s\n", teachers[i]->stu_arr[j]);
		}
	}

	//釋放
	for (int i = 0; i < 5; i++)
		for (int j = 0; j < 5; j++)
			if (teachers[i]->stu_arr[j]) free(teachers[i]->stu_arr[j]), teachers[i]->stu_arr[j] = NULL;

	for (int i = 0; i < 5; i++) if (teachers[i]) free(teachers[i]), teachers[i] = NULL;

	if (teachers) free(teachers), teachers = NULL;
	
	
	system("pause");
	return 0;
}