【408】C函数中的ADT

类似类的形式

  • boardADT.h:所有的宏、声明等部分写在这里
  • boardADT.c:只需要 #inclue "boardADT.h",不需要 include 其他系统头文件,然后在此建立 struct,类似属性的内容,建立各种函数,类似方法的内容
  • puzzle.c:只需要 #inclue "boardADT.h",main 函数在此,主要调用 ADT 中的属性和方法

在 struct 里面添加数组指针,所以只是存储地址

注意:struct 在ADT里面建立,不在 head 文件里面

另外,主函数 所在的文件不能调用 struct 里面的内容

即在主函数中不能出现 -> 的字样。。

struct board_struct {
	long* body;
	long length;
	long side;	 //length of side
	long size;
};

typedef struct board_struct *board;

在初始化的时候,首先为 bo 分配空间,包括 地址+long+long+long

然后再为 数组 bo->body 分配空间,根据具体数组大小来分配

他们的空间是分开的,因此最后需要分别释放

board init_board(long size_arg) {
	board bo;
	bo = malloc(sizeof(struct board_struct));
	if (bo == NULL){
		fprintf(stderr, "Memory allocation error.
");
		exit(EXIT_FAILURE);
	}
	bo->body = malloc(sizeof(long)*size_arg);
	if (bo->body == NULL){
		fprintf(stderr, "Memory allocation error.
");
		exit(EXIT_FAILURE);
	}
	bo->length = 0;
	bo->side = 0;
	bo->size = size_arg;
	return bo;
}

最后为board->body释放空间的时候,需要建立函数释放,因为board->body在主函数中无法调用。。

原文地址:https://www.cnblogs.com/alex-bn-lee/p/11069203.html