C语言结构体和共用体(2)

结构指针变量作函数参数:

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

      1、用结构体变量的成员作参数;

      2、结构体变量作实参;

      3;用指向结构体变量(或数组)的指针作实参,将结构体变量(或数组).

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

      方法1:用结构体变量作函数参数(传值):

#include<stdio.h>
#include<string.h>
struct student
{
    int num;
    char name[20];
    double score[3];
};
void print(struct student);
int main()
{
    struct student stu;
    stu.num=8;
    strcpy(stu.name,"aihara");//或者是将name定义为指针变量,本句改为 stu.name="aihara";
    stu.score[0]=98.5;
    stu.score[1]=99.0;
    stu.score[2]=99.5;
    print(stu);
}
void print(struct student stu)
{
    printf("\tnum     : %d\n",stu.num);
    printf("\tname    : %s\n",stu.name);
    printf("\tscore_1 : %5.2lf\n",stu.score[0]);
    printf("\tscore_2 : %5.2lf\n",stu.score[1]);
    printf("\tscore_3 : %5.2lf\n",stu.score[2]);
    printf("\n");
}

      方法二:用指向结构体变量的指针作实参(传址):

#include<stdio.h>
#include<string.h>
struct student
{
    int num;
    char name[20];
    double score[3];
};
void print(struct student *);
int main()
{
    struct student stu;
    stu.num=8;
    strcpy(stu.name,"aihara");
    stu.score[0]=98.5;
    stu.score[1]=99.0;
    stu.score[2]=99.5;
    print(&stu);
}
void print(struct student *p)
{
    printf("\tnum     : %d\n",p->num);
    printf("\tname    : %s\n",p->name);
    printf("\tscore_1 : %5.2lf\n",p->score[0]);
    printf("\tscore_2 : %5.2lf\n",p->score[1]);
    printf("\tscore_3 : %5.2lf\n",p->score[2]);
    printf("\n");
}
动态存储分配:

      C语言中不允许动态数组类型,所以对于这种问题,用数组的办法很难解决。

      所以C语言提供了一些内存管理函数,常用的有一下几个:

      1、分配内存空间的函数malloc、calloc;

      2、释放内存空间的函数free。

malloc函数:

      函数原型为 void*malloc(unsigned int size);

      其作用是在内存的动态存储区中分配一个长度为size的连续空间(size是一个无符号数)。

      此函数的返回值是一个指向分配域起始地址的指针(类型为void)。

      如果此函数未能成功地执行(例如内存空间不足),则返回空指针(NULL)。

calloc函数:

       函数原型为 void*malloc(unsigned n,unsigned size);

      其作用是在内存的动态存储区中分配n个长度为size的连续空间。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值