环境:ide:Mac+clion
视频链接:
https://www.bilibili.com/video/BV1Hb411Y7E5?p=5
数组的定义
int arr[5];//数组的定义,必须知道长度。
for (int i=0;i<sizeof(arr)/sizeof (arr[0]) ;i++){//condition 数组的长度
arr[i]= i;
cout << arr[i];
}
cout << endl;
int arr1[5] = {0,1,2,3,4};//第二种赋值方式。
int arr2[] = {0,1,2,3,4};//数组的第三种赋值方式。
练习题:找出这个数组最大值
int arr4[] = {800, 350, 200, 400, 900,250,600};
int maxValue = arr4[0];
for (int i =1;i<sizeof(arr4)/sizeof (arr4[0]);i++){
if(maxValue < arr4[i]){
maxValue = arr4[i];
}
}
cout << maxValue << endl;
冒泡排序法,按照升序排列出来
int arr[] = {4, 2, 8, 0, 5, 7, 1, 3, 9, 6};
int tmpValue = arr[0];
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
for (int j = 0; j < sizeof(arr) / sizeof(arr[0]) -1- i; j++) {
if (arr[j] > arr[j + 1]) {
tmpValue = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmpValue;
}
}
}
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) {
cout << arr[i];
}
二维数组的定义
int arr[2][3]; //两行三列,访问通过arr[0][0] 这是二维数组第一个元素。
arr[0][0] =1;
arr[0][1] =2;
arr[1][0] =3;
arr[1][1] =4;
arr[1][2] =5;
int arr2[2][3] = {
{1,2,3},
{4,5,6}
}; //第二种定义方式
for (int i = 0;i <2;i++){//行
for (int j = 0;j <3;j++){//列
arr2[i][j] = j ;
}
}
for (int i = 0;i <2;i++){//行
for (int j = 0;j <3;j++){//列
cout<<arr2[i][j] << " ";
}
cout << endl;
}
int arr[2][3] = {
{1,2,3},
{4,5,6}
};
cout<<"二维数组占用内存空间大小:"<<sizeof (arr)<<endl;
cout<<"二维数组一行占用内存空间大小:"<<sizeof (arr[0])<<endl;
cout<<"二维数组一个元素占用内存空间大小:"<<sizeof (arr[0][0])<<endl;
cout<<"二维数组首地址:"<<arr<<endl;
cout<<"二维数组首地址:"<<&arr<<endl;
cout<<"二维数组行数:"<<sizeof (arr)/sizeof (arr[0])<<endl;
cout<<"二维数组列数:"<<sizeof (arr[0])/sizeof (arr[0][0])<<endl;
练习题:计算三个人的语文/数学/英语的分数总和案例:
int scores[3][3] = { //定义二维数组
{100,100,100},
{90,90,10},
{80,70,60}
};
string names[] = {"张三","李四","王五"};
for (int i=0;i<sizeof (scores)/sizeof (scores[0]);i++){
int sum = 0;
for (int j = 0 ;j<sizeof (scores[0])/sizeof (scores[0][0]);j++){
sum += scores[i][j];
}
cout << names[i]<<"的分数总和是:"<<sum << endl;
}
函数:c++ 是值传递
int add(int x,int y);//形参
int add (int x,int y){//形参
return x + y;
}
int a = 2;
int b = 4;
int c = add(a,b);
cout << c;//6
//函数声明,告诉编译器有这么一个函数
int max(int, int);
//函数定义
int max(int x, int y) {
return x >= y ? x : y;
}
函数分文件编写:
创建.h //用来写函数声明
创建cpp 文件 //函数定义, 引入.h头文件
在main 函数中,引入.h头文件,使用该函数即可。
指针
//指针即是地址,通过*p 进行指针解引用,就是那个实际的值。
int a = 10;
int *p;//定义一个指针。
p = &a;//对指针进行地址赋值。
cout << "a的值是:"<<a<<endl;
cout << "指针的地址是:"<<p<<endl;
cout<<"a的地址是:"<<&a<<endl;
cout<<"指针对应的值是:"<<*p<<endl;
*p = 20;
cout<<"指针对应的新值是:"<<*p<<endl;
cout << "a的新值是:"<<a<<endl;
//32位系统指针的内存是4,64位系统都是内存都是8
int a = 10;
int * p = &a;
cout << sizeof (p)<<endl;
cout << sizeof (char *)<<endl;
cout << sizeof (double *)<<endl;
cout << sizeof (float *)<<endl;
//空指针和野指针: 空指针用于给指针变量初始化,空指针是不允许进行访问的。
// 0 -255 的内存编号是系统占用的,不能访问它。
int * p1 = NULL;
//cout << *p << endl; // 这里报错。
//野指针,是指向的非法的地址。 避免出现野指针。
p1 = (int *)0x1100;
cout << *p1 << endl; // 这里报错。没权限访问。
网友评论