Chinaunix首页 | 论坛 | 博客
  • 博客访问: 336812
  • 博文数量: 92
  • 博客积分: 2500
  • 博客等级: 少校
  • 技术积分: 960
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-21 19:38
文章分类

全部博文(92)

文章存档

2010年(71)

2009年(21)

我的朋友

分类: 嵌入式

2010-06-12 15:33:06

结构体

结构体数组

struct student

     int num

?

         };

 struct student str[]{{…},{…},{…}}   

    即先声明结构体类型,然后定义数组为该结构体类型,在定义数组时初始化。

 

11.2对候选人得票的统计程序。设有3个候选人,每次输入一个得票的候选人的名字,要求最后输出各人得票结果。
#include ?
#include
struct person
 {
   char name[20];in count;
  };
struct person leader[3]={{
Li,0}, { Zhang,0}, { Fun,0}};

void main()
{ int i,j;  char leader_name[20];
  for(i=1;i<=10;i++)
   {
    scanf(
%s
,leader_name); 
      for(j=0;j<3;j++)
     
 if(strcmp(leader_name,leader[j].name)==0)
        
leader[j].count++;
    }
   printf(
\n);
  for(i=0;i<3;i++)     printf(
%5s:%d\n,leader[i].name,leader[i].count);}

 

 

 

结构体指针

以下3种形式等价:

结构体变量.成员名

②(*p).成员名

     ->成员名

 

 

例11.3指向结构体变量的指针的应用
#include
?
#include
void main()
{struct student{long num;char name[20];
                   char   sex; float score;};
       
struct student stu_1;
        struct student* p; p=&stu_1;
      stu_1.num=89101;strcpy(stu_1.name,
LiLin);
      stu_1.sex=
M
;stu_1.score=89.5;
    printf(
No.:%ldnname:%snsex:%cnscore:%fn″,stu-1.numstu-1.namestu-1.sex
stu-1.score);
    printf(
No.:%ldnname:%snsex:%cnscore:%fn″,(*p).num(*p).name(*p).sex
(*p).score); 
}

 

也可以是  p->num, p->name

 

 

 

注意:

   (2) 程序已定义了p是一个指向struct student类型数据的指针变量,它用来指向一个struct student类型的数据,不应用来指向stu数组元素中的某一成员。

例如:  p=stu[1].name;

    如果要将某一成员的地址赋给p可以用强制类型转换,先将成员的地址转换成p的类型。

例如:p=(struct student *)stu[0].name;

 

 

带结构体参数的函数

void main()
{
      
void print(struct student);
       struct student stu;
       stu.num=12345;strcpy(stu.name,
LiLin;stu.score[0]=67.5;stu.score[1]=89;stu.score[2]    =78.6);
       print(stu);
}
void print(struct student stu)
{  printf(FORMAT
stu.numstu.name stu.score[0] stu.score[1]stu.score[2]);
      printf
(″\n″);}

 

带结构体指针参数的函数

#include
struct student
{
           int num;
           char name[20];
           float score[3];
};stu={12345,
LiLi
,67.5,89,78.6};
void main()
{
void print(struct student *);
                              /*
形参类型修改成指向结构体的指针变量*/
         print(&stu);}               /*
实参改为stu的起始地址*/


void print(struct student *p)                    /*
形参类型修改了*/
{                      printf(FORMAT
p->nump->name
 
      p->score
0],p->score1],p->score2]);
                        
                                                  /*
用指针变量调用各成员的值
*/
 printf
(″\n″);}

 

阅读(1322) | 评论(0) | 转发(0) |
0

上一篇:带参数的函数

下一篇:链表

给主人留下些什么吧!~~