码迷,mamicode.com
首页 > 其他好文 > 详细

结构体参数

时间:2019-07-14 11:17:29      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:print   set   定义   include   ike   pre   有关   color   使用   

结构体作为函数参数:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct student
{
    char name[10];
    int age;
};

void print_student(struct student s)
{
    printf("name = %s,age = %d\n",s.name,s.age);
}    

void set_student(struct student *s,char *name,int age)
{
    strcpy(s->name,name);
    s->age = age;
}

int main()
{
    struct student st = {"tom",20};
    set_student(&st,"mike",100);
    print_student(st);
    return 0;
}

结构体作为函数参数时,实参传入地址,形参用指针接收。

 

运行结果;

exbot@ubuntu:~/wangqinghe/C/20190714$ ./struct2

name = mike,age = 100

 

如果函数参数的结构特别大,比如name[10000],会导致入栈速度变得很大,栈的内存变得很大,程序运行效率很低,所以一般来说不要把结构变量作为函数参数传递。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct student
{
    char name[10];
    int age;
};

void print_student(const struct student *s)
{
    printf("name = %s,age = %d\n",s->name,s->age);
}    

void set_student(struct student *s,char *name,int age)
{
    strcpy(s->name,name);
    s->age = age;
}

int main()
{
    struct student st = {"tom",20};
    set_student(&st,"mike",100);
    print_student(&st);
    return 0;
}

运行结果:exbot@ubuntu:~/wangqinghe/C/20190714$ gcc struct2.c -o struct2

exbot@ubuntu:~/wangqinghe/C/20190714$ ./struct2

name = mike,age = 100

 

结论:在定义一个和结构体有关的函数时,尽量使用指针,而不是使用结构变量。因为使用指针,只需要传递地址大小的数据。

结构体参数

标签:print   set   定义   include   ike   pre   有关   color   使用   

原文地址:https://www.cnblogs.com/wanghao-boke/p/11183150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!