zoukankan      html  css  js  c++  java
  • 结构指针变量作函数参数

    将一个结构体变量的值传递给另一个函数,有3种方法:

    (1)用结构体变量的成员做参数。

    (2)用结构体变量做实参。

    (3)用指向结构体变量的指针做实参,将结构体变量的地址传给形参。

    例:有一个结构体变量stu,内含学生学号、姓名和3门课程的成绩。通过调用函数print将他们输出。

    要求:用结构体变量做函数实参:

    #include "StdAfx.h"
    #include<stdio.h>
    #include<string.h>
    struct student
    {
        int num;
        char name[20];
        float score[3];
    };
    void print(struct student);
    void main()
    {
        struct student stu;
        stu.num=8;
        strcpy(stu.name,"lv");    //若直接赋值,则name必须为指针
        stu.score[0]=98.5;
        stu.score[1]=99.0;
        stu.score[2]=99.5;
        print(stu);
    }
    void print(struct student stu)
    {
        printf("	 num:%d
    ",stu.num);
        printf("	name:%s
    ",stu.name);
        printf("	score_1:%5.2f",stu.score[0]);
        printf("	score_2:%5.2f",stu.score[1]);
        printf("	score_3:%5.2f",stu.score[2]);
    }

    用指向结构体变量的指针做实参:

    #include "StdAfx.h"
    #include<stdio.h>
    #include<string.h>
    struct student
    {
        int num;
        char name[20];
        float score[3];
    };
    void print(struct student*);
    void main()
    {
        struct student stu;
        stu.num=8;
        strcpy(stu.name,"lv");    //若直接赋值,则name必须为指针
        stu.score[0]=98.5;
        stu.score[1]=99.0;
        stu.score[2]=99.5;
        print(&stu);
    }
    void print(struct student *stu)
    {
        printf("	 num:%d
    ",stu->num);
        printf("	name:%s
    ",stu->name);
        printf("	score_1:%5.2f",stu->score[0]);
        printf("	score_2:%5.2f",stu->score[1]);
        printf("	score_3:%5.2f",stu->score[2]);
    }
  • 相关阅读:
    select_tag in rails about selected not change and onchange()
    debian7 请把标有“Debian GNU/Linux 7.1.0 _Wheezy_
    rails关于utf8问题-------------------utf8申明必须置顶
    ruby 删除文件
    svn conflict
    40亿个有序不同的数的文件中找一个缺失的数
    马云语录
    语音识别概率问题,一段在数学之美了看到的话
    两个有序数组的中位数
    磁盘文件排序-编程珠玑
  • 原文地址:https://www.cnblogs.com/lvfengkun/p/10389992.html
Copyright © 2011-2022 走看看