结构与函数

结构作为函数参数

函数类型 函数名(struct 结构名 变量名,...){}
  • 结构的值可以直接作为参数传入

  • 此时是在函数内新建了一个结构,并复制传入的值

  • 传入函数的结构在函数中只在值上等于原结构

  • 函数可以return一个结构

函数可以返回一个结构

struct 结构名 函数名(...){
    struct 结构名 变量名;
    return 变量名;
}

举个例子

#include<stdio.h>
struct info getInfo(void);

struct info {
    char name[5];
    int age;
    int id;
};

int main(){
    struct info student;
    student = getInfo();
    printf("姓名\t年龄\t学号\n%s\t%d\t%d\n",\
            student.name,student.age,student.id);
    return 0;
}

struct info getInfo(void){
    struct info t;
    scanf("%s%d%d",t.name,&t.age,&t.id);
    return t;
}

在这个例子中,getInfo返回了一个结构,并赋给了student变量.

结构指针作为参数

  • 相对于上面的方法,结构指针作为参数更推荐使用.

K & R

"If a large structure is to be passwd to a func, it's generally more efficent to pass a pointer than to copy whe whole structure"

  • 对于一个函数指针,可以用 -> 运算符访问指针所指结构下的成员.

因此,我们可以把上一个的例子修改为:

#include<stdio.h>
struct info* getInfo(struct info *t);
void printInfo(struct info *t);

struct info {
    char name[5];
    int age;
    int id;
};

int main(){
    struct info student;
    printInfo(getInfo(&student));
    return 0;
}

struct info* getInfo(struct info *t){
    scanf("%s%d%d",t->name,&t->age,&t->id);
    return t;
}

void printInfo(struct info *t){
    printf("姓名\t年龄\t学号\n%s\t%d\t%d\n",\
            t->name,t->age,t->id);
}
最后修改:2023 年 04 月 28 日
如果觉得我的文章对你有用,请随意赞赏