一、局部变量和全局变量
1.局部变量:在还是内部定义的变量
*作用域:从定义变量开始,到代码块结束
*生命周期:定义开始到代码块结束,就会被回收
*函数的形参也是局部变量
*无固定初值
2.全局变量:函数外面定义的变量
*作用域:定义开始到文件结尾(能被后面所有函数共享)
*生命周期:程序一开始就分配内存,到程序退出才销毁
*默认的初值为0
#include<stdio.h>
int age;
void test(){
int age;
age=10;
}
int main(){
printf("%d\n",age);//0int age=20;
printf("%d\n",age);//20
test();//直接调用函数
printf("%d\n",age);//20
return 0;
}
二、结构体
1、构造类型:数组、结构体
#include<stdio.h>
int main(){
//1>.定义结构体类型,例
struct Person{//结构体里面的3个变量称为结构体的成员或者属性
int age;//年龄
double height;//身高
char *name;//姓名
};
struct Person p={ 20,1055,"jack"};
p.age=30;
p.name="rose";
printf("age=%d,name=%s,height=%f\n",p.age,p.name,p.height);
/*错误写法
struct Person p1;
p1={30,1.69,"jack"};
*/
struct Person p2={.age=30,.height=1.69,.name="jack"};
return 0;
}
#include<stdio.h>
int main(){
void test(){//补齐算法(对齐算法),结构体所占内存空间必须是最大成
员字节数的倍数,所以本结构体占16个字节的内存空间
struct Student{
int age;//4个字节
char name;//8个字节
};
}
void test1(){
//1.定义结构体类型
struct Date{
int year;
int mouth;
int day;
};
//2.定义结构体变量(真正分配内存空间)
struct Date d1={ 2011,10,3};
struct Date d1={ 2012,5,12};
d2=d1;//会将d1所有成员的值对应的赋值给d2的所有成员的值
d2.year=2010;
printf("%d-%d-%d\n"d1.year,d1.mouth,d1.day);
printf("%d-%d-%d\n"d2.year,d2.mouth,d2.day);
}
return 0;
}
2、定义变量的三种方式
#include<stdio.h>
int main(){
//第三种方式
struct {
int age;
double height;
char *name;
}stu;
//第二种方式:定义类型的同时,定义了变量
struct Student{
int age;
double height;
char *name;
}stu;
/*
//第一种方式
struct Student{
int age;
double height;
char *name;
};//变量
struct Student stu={30,1.69,"jack"};
*/
return