zoukankan      html  css  js  c++  java
  • C语言 结构体作为函数的参数

    1)使用结构体变量作为函数的参数

      使用结构体变量作为函数的实参时,采用的是值传递,会将结构体变量所占内存单元的内容全部顺序传递给形参,形参必须是同类型的结构体变量

    demo:

     1 # include <stdio.h>
     2 # include <stdlib.h>
     3 
     4 //创建一个Student结构 
     5 struct Student
     6 {
     7     char name[30];
     8     float fScore[3];
     9 }student={"dire",98.5,89.0,93.5}; //初始化结构体变量 
    10 
    11 void Display(struct Student su) //形参为同类型的结构体(Student结构) 
    12 {
    13     printf("-----Information------
    ");
    14     printf("Name:%s",su.name);
    15     printf("Chinese:%.2f
    ",su.fScore[0]);
    16     printf("Math:%.2f
    ",su.fScore[1]);
    17     printf("English:%.2f",su.fScore[2]);
    18     printf("平均分数为:%.2f
    ",(su.fScore[0]+su.fScore[1],su.fScore[2])/3);
    19 }
    20 
    21 int main ()
    22 {
    23     
    24     Display(student);
    25     
    26     return 0;
    27  } 

    Printf:


    2)使用指向结构体变量的指针作为函数参数

    Demo:

     1 # include <stdio.h>
     2 # include <stdlib.h>
     3 
     4 struct Student {
     5     char name[20];
     6     float fScore[3];
     7 }student = {"dire",98.5,89.0,93.5}; //初始化结构体变量 
     8 
     9 
    10 void Display(struct Student *pStruct)
    11 {
    12     printf("------Information-------
    ");
    13     printf("Name:%s
    ",pStruct->name);
    14     printf("Chinese:%.2f
    ",(*pStruct).fScore[0]);
    15     printf("Math:%.2f
    ",(*pStruct).fScore[1]);
    16     printf("English:%.2f
    ",pStruct->fScore[2]);
    17 }
    18 
    19 
    20 int main ()
    21 {
    22     Display(&student);        //将结构体变量的首地址作为实参传入pStruct指针变量中 
    23     
    24     return 0;
    25 } 

    3)使用结构体变量的成员作为函数参数

      这种方式为函数传递参数与普通的变量作为实参是一样的,是值传递

  • 相关阅读:
    二叉排序树 常用函数小结
    二叉树的应用:二叉排序树的删除
    剑指 Offer 32
    剑指 Offer 32
    剑指 Offer 68
    剑指 Offer 28. 对称的二叉树 做题小结
    正则表达式不要背
    剑指 Offer 55
    LeetCode226. 翻转二叉树 做题小结
    Tools | 编程IED/编译器
  • 原文地址:https://www.cnblogs.com/dire/p/5224609.html
Copyright © 2011-2022 走看看