设为首页 加入收藏

TOP

C语言结构体相关函数 指针(二)
2014-04-06 17:42:09 来源: 作者: 【 】 浏览:781
Tags:语言 结构 相关 函数   指针

 

  结构体指针访问 :

  -- 示例 : 定义一个结构体指针;

  struct student

  {

  char *name;

  int age;

  }*p;

  -- . 和 ->优先级 : 这两个运算符都是从左到右运算, 都是右结合;和 -> 优先级比 * , ++ 优先级要高; 这两个运算符与 () [] 是四个优先级最高的运算符;

  -- ++p->age 分析 : 是对结构体中的 age 进行自增操作;

  -- *p->name 分析 : 获取 结构体中的 name 字符串的值(注意不是指针|地址);

  -- *p++->name 分析 : 先获取 name 字符串的值, 再将p自增;

  结构体函数示例 :

  #include<STDIO.H>

  /*声明一个结构体类型, 其成员变量是普通变量*/

  struct student

  {

  char *name;

  int age;

  };

  /*声明一个结构体类型, 其成员变量是结构体*/

  struct class

  {

  struct student s1;

  struct student s2;

  };

  /*

  * 传递 2 个结构体的成员变量

  * 在函数中创建结构体并返回

  */

  struct student create_student(char *name, int age)

  {

  struct student s1 = {name, age};

  return s1;

  }

  /*

  * 传递 2 个结构体变量

  */

  struct class create_class(struct student s2, struct student s3)

  {

  struct class c1 = {s2, s3};

  return c1;

  }

  /*

  * 传入一个结构体指针

  * 通过指针访问结构体的方法 :

  *   (*结构体指针变量)。成员变量 访问;

  *   结构体指针变量 -> 成员变量 访问;

  */

  void printf_struct_pointer(struct student *s)

  {

  printf(student : (*s)。name = %s, (*s)。age = %d

  , (*s)。name, (*s)。age);

  printf(student : s->name = %s, s->age = %d

  , s->name, s->age);

  }

  int main(int argc, char **argv)

  {

  /*使用函数获取一个结构体, 传入结构体的值*/

  struct student s1 = create_student(Tom, 11);

  printf(student : name = %s, age = %d

  , s1.name, s1.age);

  /*创建一个成员变量是结构体的结构体, 并打印结构体数据*/

  struct class c1 = create_class(create_student(Jack, 12), create_student(CJ, 13));

  printf(c1 : s1 : name = %s, age = %d ; s2 : name = %s, age = %d

  , c1.s1.name, c1.s1.age, c1.s2.name, c1.s2.age);

  /*声明结构体指针*/

  struct student *p = &s1;

  printf_struct_pointer(p);

  return 0;

  }</STDIO.H>

  执行结果 :

  #include<STDIO.H>

  /*

  * 声明结构体

  * 同时也声明结构体类型数组

  * 为数组初始化

  * 直接将每个结构体成员的值依次列出即可

  */

  struct student

  {

  char *name;

  int age;

  } team1[] =

  {

  Tom, 12,

  Jack, 13

  };

  int main(int argc, char **argv)

  {

  int i;

  /*将每个结构体初始化, 赋值, 每个结构体初始化内容使用 花括号括起来*/

  struct student team2[] = {{CJ, 34}, {KI, 32}};

  for(i = 0; i < 2; i++)

  {

  printf(team1 : team1[i].name = %s, team1[i].age = %d

  , team1[i].name, team1[i].age);

  }

  for(i = 0; i < 2; i++)

  {

  printf(team2 : team2[i].name = %s, team2[i].age = %d

  , team2[i].name, team2[i].age);

  }

  return 0;

  }

  </STDIO.H>

              

首页 上一页 1 2 3 4 5 6 下一页 尾页 2/6/6
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇关于C语言中二维数组传参 下一篇简单C++程序—掷骰子

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: