数组
什么是数组?
一组相同类型元素的集合
数组的定义
int arr[10]={1,2,3,4,5,6,7,8,9,10}; //定义一个整型数组,最多放10个元素
注意数组的大小是常量,不能是变量
错误示范:
int main()
{
int n=10;
int arr[n]={0};
return 0;
}
练习
C语言中下面那个数组的创建是错误的()
A:int arr[10]={0};
B:int n=10; int arr[n]={0};
C:int arr[]={1,2,3,4,5,6,7,8,9,10};
D:char ch[15]=“hello word”;
答案:B
A 数组创建10个整型元素 没问题
B 数组的大小用常量来指定,而n是变量 错误
C 这个数组虽然没有指定大小,但是后面初始化了,初始化的内容可以确定数组的大小 没问题
D 字符数组里面可以放一个hello word这个字符串 没问题
用函数求两个数的较大值
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int Add(int a,int b){
if (a>b)
{
return a;
}
else
{
return b;
}
}
int main()
{
int num1=50;
int num2=30;
int max=Add(num1,num2);
printf("max=%d\n",max);
return 0;
}
关键字
typedef
顾名思义是类型的定义,这里应该理解为类型重命名
int main()
{
typedef int u_int;
int num1=20;
u_int num2=30;
printf("%d\n",num2);
return 0;
}
static
在C语言中:
static是用来修饰变量和函数的
1.修饰局部变量—静态局部变量
2.修饰全局变量—静态全局变量
3.修饰函数—静态函数
static修饰局部变量
void test()
{
int a=1;
a++;
printf("a=%d\n",a);
}
int main()
{
int i=0;
while (i<5)
{
test();
i++;
}
return 0;
}
void test()
{
static int a=1;
a++;
printf("a=%d\n",a);
}
int main()
{
int i=0;
while (i<5)
{
test();
i++;
}
return 0;
}
static 修饰局部变量,局部变量的生命周期变长。
static修饰全局变量
test1
int main()
{
//extern - 关键字 声明外部符号的
extern int val;
printf("%d\n",val);
return 0;
}
test2
#define _CRT_SECURE_NO_WARNINGS 1
int val=2020;
在test2加上static
#define _CRT_SECURE_NO_WARNINGS 1
static int val=2020;
static修饰全局变量
改变了变量的作用域 — 让静态的全局变量只能在自己所在的源文件内部使用,出了源文件就没法使用了
static修饰函数
test1
//声明外部函数
extern int Add(int,int);
int main()
{
int a=20;
int b=30;
int sum=Add(a,b);
printf("sum=%d\n",sum);
return 0;
}
test2
int Add(int a,int b)
{
int c=a+b;
return c;
}
在test2加上static
static int Add(int a,int b)
{
int c=a+b;
return c;
}
static修饰函数改变了函数的链接属性
正常的函数是具有外部链接属性,外部的其他源文件只要声明它就可以使用,如果被static修饰了就变成了内部链接属性