定义
存储类:即存储模型 自动、寄存器、具有外部链接的静态、具有内部链接的静态、空链接的静态,还有基于指针的类型。
作用域:作用范围
链接 : 是否可被外部引用
存储时期:变量在内存中保留的时间
作用域
代码块作用域:即方法体等类似范围
函数原型作用域:函数声明时范围
文件作用域:文件内函数外声明的范围,可被内部任何地方和其他文件引用,也称全局变量
链接
外部链接: 文件作用域,不用static
修饰
内部链接: 文件作用域,使用static
修饰
空链接: 代码块作用域 和 函数原型作用域 变量具有空链接
存储时期
静态存储时期: 静态变量在程序执行期间一直存在,具有文件作用域变量具有静态存储时期。
自动存储时期: 局部变量属于自动类型。
存储类
- 寄存器变量 比自动变量访问快、无法获取地址
- 代码块作用域的静态变量
- 外部链接的静态变量 extern声明在其他文件中定义的变量
- 具有内部链接的静态变量
#include <stdio.h>
void count();
int main(int argc, char *argv[])
{
count();
count();
return 0;
}
void count()
{
// 代码块作用域的静态变量
static int count = 0;
count++;
printf("count = %d
", count);
}
函数示例
掷骰子,随机数生成
头文件 dice.h
int roll(int max);
extern int count;
实现 dice.c
#include "dice.h"
#include <stdio.h>
#include <stdlib.h>
int count;
int roll(int max)
{
count++;
return rand() % max + 1;
}
调用 main.c
#include "dice.h"
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("掷骰子 1 次 : %d
", roll(100));
printf("掷骰子 2 次 : %d
", roll(100));
printf("总次数 : %d
", count);
return 0;
}
内存管理 malloc() 和 free()
创建动态数组,记得要free释放
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
double * money;
int max;
int number;
int i = 0;
puts("要整个多大的数组啊?");
scanf("%d", &max);
money = (double *)malloc(max * sizeof(double)); // 类型指派 c不是必要,c艹必要
if (NULL == money)
{
puts("空间不足");
exit(EXIT_FAILURE);
}
puts("往数组放数吧
");
while (i < max && scanf("%lf", &money[i]) == 1)
{
i++;
}
printf("你输入的是: %d
", number = i);
for (i = 0; i < number; i++)
{
printf("%7.2f ", money[i]);
}
puts("over.
");
free(money);
return 0;
}
console: