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)使用结构体变量的成员作为函数参数

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

  • 相关阅读:
    self 和 super 关键字
    NSString类
    函数和对象方法的区别
    求两个数是否互质及最大公约数
    TJU Problem 1644 Reverse Text
    TJU Problem 2520 Quicksum
    TJU Problem 2101 Bullseye
    TJU Problem 2548 Celebrity jeopardy
    poj 2586 Y2K Accounting Bug
    poj 2109 Power of Cryptography
  • 原文地址:https://www.cnblogs.com/dire/p/5224609.html
Copyright © 2011-2022 走看看