Talk is cheap,show me the code.
结构体
#include <stdio.h>
struct student//定义一个新的类型(分配空间的模板)
{
int id;
char name[10];
char addr[100];
short c_sore;
};
typedef struct student stu;//stu就是student的别名
void main()
{
//基本用法
struct student a1;//定义变量,分配空间
// a1={17002,"123","456",100}; 错误,只能在定义时初始化,或在之后逐一赋值
struct student a2={17002,"cmz","wuhan",100};//初始化
printf("%d",a2.id);//引用
//指针
struct student *pst=&a2;
printf("%d\n",sizeof(pst));//4
printf("%d %s %s %d\n",pst->id,(*pst).name,pst->addr,(*pst).c_sore);
//数组
stu e1702[10]={ {17001,"yha","wuhan",98},{17003,"hello","hankou",90},
{17001,"yha","wuhan",98},{17003,"hello","hankou",90},
{17001,"yha","wuhan",98},{17003,"hello","hankou",90},
{17001,"yha","wuhan",98},{17003,"hello","hankou",90},
{17007,"haha","iam",98},{17003,"hello","hankou",90}
};
int buf[10]={1,2,3,4,5,6,7,8,9,0};
printf("%s %d %s\n",e1702[0].name,e1702[0].id,e1702[0].addr);//下标法
printf("%s%d %s\n",(e1702+1)->name,(e1702+1)->id,(e1702+1)->addr);//指针
//查找17007的个人信息,如果成功,则打印17007所有信息
int i,flag=0;
for(i=0;i<10;i++)
{
if(e1702[i].id==17007)
{
flag=1;
printf("%d号学生的信息为:",e1702[1].id);
printf("%s %s %d\n",e1702[i].name,e1702[i].addr,e1702[i].c_sore);
break;//退出循环
}
}
if (flag==0)
printf("没有该学生的信息\n");
}
注:分配空间时,会以字节对齐进行分配空间
1、 以最大类型长度作为单位分配空间
2、 如果此成员分配的空间足够供下一个成员使用,则共享此空间
struct student
{
int id; //4个
char name; //4个与后面共享
char addr;
short c;
};
//sizeof(struct student)为8
***栈***
头文件
#ifndef _STACK_DEF_
#define _STACK_DEF_
#define false 0
#define true 1
#define MAXSIZE 10
typedef char BOOL;
typedef int StackType;
//模型:新的类型
struct stack
{
StackType buf[MAXSIZE];
int top;//指向栈顶元素
};//一个容器
extern BOOL initStack(struct stack*);//初始化
extern BOOL isEmpty(struct stack*);//判断空
extern BOOL isFull(struct stack*);//判断满
extern BOOL push(struct stack*,StackType);//进栈
extern BOOL pop(struct stack*,StackType*);//出栈
#endif
主函数
#include"stack.h"
#include<stdio.h>
/********(1)初始化栈***********/
BOOL initStack(struct stack* ps)
{
//初始化top值,指向空
ps->top=-1;
return true;
}
/******(2)判断是否为空******/
//返回值:空-true 非空-false
BOOL isEmpty(struct stack* ps)
{
//左值尽可能为常量(在等于运算符中)
if(-1==ps->top)
{
return true;
}
return false;
}
/*******(3)是否为满********/
BOOL isFull(struct stack* ps)
{
if(MAXSIZE-1==ps->top)
return true;
else
return false;
}
/******(4)压栈*********/
//前提:不能为满
BOOL push(struct stack* ps,StackType data)
{
if(isFull(ps))//判断为满
return false;//压栈失败
ps->buf[ ++(ps->top) ]=data;//前自加:先自加,再取值
return true;//压栈成功
}
/******(5)出栈*******/
//前提:不能为空
BOOL pop(struct stack* ps,StackType* pdata)
{
if(isEmpty(ps))
return false;
//取出栈顶
*pdata=ps->buf[ ps->top-- ]; //后自减:先取值,后自减
//出栈成功
return true;
}
void main()
{
struct stack s;
initStack(&s);
push(&s,1);
push(&s,2);
push(&s,3);
StackType data;
while(pop(&s,&data))
{
printf("%d",data);
}
putchar(10);//换行
}