结构体与函数

#include <stdio.h>

struct Student

{

    int age;

    int no;

};

 

// 如果结构体作为函数参数,只是将实参结构体所有成员的值对应地赋值给了形参结构体的所有成员

// 修改函数内部结构体的成员不会影响外面的实参结构体

void test(struct Student s)

{

    s.age = 30;

    s.no = 2;

}

 

// 会影响外面的实参结构体

void test2(struct Student *p)

{

    p->age = 15;

    p->no = 2;

 

}

 

void test3(struct Student *p)

{

    struct Student stu2 = {15, 2};

    p = &stu2;

    p->age = 16;

    p->no = 3;

}

 

int main()

{

    struct Student stu = {28, 1};

    

    //test(stu);

    //test2(&stu);

    test3(&stu);

    

    printf("age=%d, no=%d\n", stu.age, stu.no);

    

    return 0;

}

 

结构体与函数例子2

 

 

 

#include <stdio.h>

 

 

 

int main()

 

{

 

    struct Date

 

    {

 

        int year;

 

        int month;

 

        int day;

 

    };

 

   // 类型

 

    struct Student

 

    {

 

        int no; // 学号

 

        

 

        struct Date birthday; // 生日

 

        

 

        struct Date ruxueDate; // 入学日期

 

        

 

        // 这种写法是错误的

 

        //struct Student stu;

 

    };

 

    struct Student stu = {1, {2000, 9, 10}, {2012, 9, 10}};

 

     printf("year=%d,month=%d,day=%d\n", stu.birthday.year, stu.birthday.month, stu.birthday.day);

 

   return 0;

 

}

 

posted @ 2016-03-28 10:06  lance.xiang  阅读(609)  评论(0)    收藏  举报