lijifeng

导航

黑马程序员——C语言基础 变量类型 结构体

                                 (以下内容是对黑马苹果入学视频的个人知识点总结)

(一)变量类型

1)局部变量

1> 定义:在函数内部定义的变量,称为局部变量。形式参数也属于局部变量。

2> 作用域:局部变量只在定义它的函数内部有效,即局部变量只有在定义它的函数内部使用,其它函数不能使用它。

3>生命周期:从定义变量的那一行开始分配存储空间,代码块结束后,就会被回收

 2)全局变量

1> 定义:在所有函数外部定义的变量,称为全局变量。

2> 作用域:全局变量的作用范围是从定义变量的位置开始到源程序结束,即全局变量可以被在其定义位置之后的其它函数所共享。

3>生命周期:程序一启动就会分配存储空间,程序退出时才会被销毁

 1 #include <stdio.h>
 2 
 3 int age; // 全局变量
 4 
 5 void test()
 6 {
 7     int age; //局部变量
 8     age = 10;
 9 }
10 
11 int main()
12 {
13     printf("%d\n", age);// 0
14     
15     int age = 20;
16     
17     printf("%d\n", age);// 20
18     
19     test();
20     
21     printf("%d\n", age);// 20
22     return 0;
23 }

(二) 结构体

1)结构体的定义

结构体内部的元素,也就是组成成分,我们一般称为"成员"。

结构体的一般定义形式为:

 1 struct 结构体名{
 2      
 3      类型名1 成员名1;
 4      
 5      类型名2 成员名2;
 6      
 7      ……
 8      
 9      类型名n 成员名n;   
10      
11  };

第一行是关键字加结构体名

2)结构体变量

先定义结构体类型在定义变量来使用

1 struct Student {
2      char *name;
3      int age;
4  };
5  
6  struct Student stu;

3)结构体使用的一些注意事项

1>不允许本身递归定义

2>结构体内可以含有别的结构体,可以嵌套定义

3>定义结构体类型是并没有分配空间,只有当定义变量时才会分配空间给该变量

4>结构体占用的内存空间是它所含所有内存之和,而且成员之间是按顺序排列的

#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 = {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;
}

 

4)结构体的初始化

将各成员的初值,按顺序地放在一对大括号{}中,并用逗号分隔,一一对应赋值。

1 struct Student {
2      char *name;
3      int age;
4  };
5  
6  struct Student stu = {"MJ", 27};

5)结构体的使用

1>一般对结构体变量是以成员单位进行的

2>对某个成员变量也是结构体变量们可以连续使用“.”来访问

3>可以对结构体进行整体赋值

 1 struct Student {
 2      char *name;
 3      int age;
 4  };
 5  
 6  struct Student stu1 = {"MJ", 27};
 7  
 8  // 将stu1直接赋值给stu2
 9  struct Student stu2 = stu1;
10  
11  printf("age is %d", stu2.age);

4>结构体可以作为数组

定义的形式和结构体一样

1  struct RankRecord records[3] =
2     {
3         {1, "jack", 5000},
4         
5         {2, "jim", 500},
6         
7         {3, "jake",300}
8     };

5>结构体作为函数参数

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

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

#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;
}

 

posted on 2015-03-23 18:22  lijifeng  阅读(177)  评论(0编辑  收藏  举报