C和指针 学习笔记-4.函数
參数传递:
參数传递採用按值传递
ADT&黑盒
ADT:abstract data type,抽象数据类型
c能够用于设计与实现抽象数据类型,由于它能够限制函数和数据定义的作用域。这样的技巧也称为黑盒设计
user.h
#define MAXLEN 3 struct UserClz { char *name; char *phone; char *address; }; typedef struct UserClz User; /* *接函数 *通地名称查找地址 */ char const * lookupAddress(char const *name); /* *接函数 *通地名称查找电话 */ char const * lookupPhone(char const *name);
user.c#include "user.h" #include <stdlib.h> #include <string.h> /* *限制訪问范围 */ static User users[MAXLEN]={ {"user1","111","aaa"}, {"user2","222","bbb"}, {"user3","333","ccc"} }; void init(){ int j=0; for(j=0;j<MAXLEN;j++){ printf("\n"); printf("name:||%s||\n",users[j].name); printf("phone:||%s||\n",users[j].phone); printf("addr:||%s||\n",users[j].address); } } /* *限制訪问范围 */ static User const * getUserByName(char const *name){ User const *pu; pu=users; int i ; for(i=0;i<MAXLEN;i++){ if(strcmp((pu+i)->name,name)==0){ return pu+i; } } return NULL; } char const * lookupPhone(char const *name){ User const *pu; pu=getUserByName(name); if(pu!=NULL){ return pu->phone; }else { return NULL; } } char const * lookupAddress(char const *name){ User const *pu; pu=getUserByName(name); if(pu!=NULL){ return pu->address; }else { return NULL; } }
main.c#include <stdio.h> #include "user.c" void main(){ init(); printf("phone=%s\n",lookupPhone("user1")); printf("address=%s\n",lookupAddress("user2")); }
以上就是黑盒的样例,墨盒的功能通过规定的接口訪问模块,接口函数lookupPhone与lookupAddress,
用户不能直接訪问和模块实现相关的数据,如:users,getUserByName,它们被声明为static
递归
求菲波那契数
#include <stdio.h> int fn(int n){ if(n<=2) return 1; return fn(n-1)+fn(n-2); } void main(){ printf("result:%d\n",fn(5));// result:5 }
过程图
posted on 2019-05-13 20:12 xfgnongmin 阅读(123) 评论(0) 编辑 收藏 举报