目录
1.3、指针所占内存空间:32位操作系统下占4个字节;64位系统下占8个字节。
1.4.3、总结:空指针和野指针都不是我们申请的空间,因此不要访问。
2.2.1、语法:struct 结构体名 { 结构体成员列表 };
2.3.2、语法:struct 结构体名 数组名[ 元素个数 ] = { {},{},...};
2.4.2、利用操作符 -> 可以通过结构体指针访问结构体属性;
一、指针
1.1、指针的作用:可以通过指针间接访问内存;
a)内存编号是从0开始记录的,一般用十六进制数字表示;
b)可以利用指针变量保存地址。
1.2、指针变量的定义和使用
1.2.1、指针变量定义的语法:数据类型 * 变量名 ;
1.2.2、指针变量解引用:* 指针变量名
int main(){
//1、指针的定义
int a = 10;
int * p ;
p = &a;
cout << &a << endl;
cout << p << endl;
//2、指针的使用
cout << "*p = " << *p << endl;
system("pause");
return 0 ;
}
1.3、指针所占内存空间:32位操作系统下占4个字节;64位系统下占8个字节。
1.4、空指针和野指针
1.4.1、空指针:指针变量指向内存中编号为0的空间;
用途:初始化指针变量;
注意:空指针指向的内存是不可以访问的
1.4.2、野指针:指针变量指向非法的内存空间;
1.4.3、总结:空指针和野指针都不是我们申请的空间,因此不要访问。
1.5、const 修饰指针
const 修饰指针有三种情况:
1.5.1、const 修饰指针 —— 常量指针:
//示例
const int * p = &a;
特点:指针的指向可以改,但是指针指向的值不可以改;
1.5.2、const 修饰常量 —— 指针常量:
//示例:
int * const p = &a;
特点:指针的指向不可以改,但是指针指向的值可以改;
1.5.3、const 修饰指针也修饰常量:
//示例
const int * const p = &a;
特点:指针的指向和指向的值都不可以改。
1.6、指针访问数组
1.7、指针访问函数
a)值传递不改变实参;
b)地址传递改变实参。
数组、函数、指针 综合实例:
#include<iostream>
using namespace std;
void bubbleSort(int * arr,int len)
{
for (int i = 0; i < len - 1; i++)
{
for(int j = 0;j < len - i - 1;j++)
{
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArr(int* arr, int len)
{
for (int i = 0; i < len; i++)
{
cout << arr[i] << endl;
}
}
int main()
{
int arr[10] = { 9,5,6,7,1,4,3,2,8,0};
int len = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr,len);
printArr(arr,len);
system("pause");
return 0;
}
二、结构体
2.1、结构体基本概念
结构体属于用户自定义的数据类型,允许用户存储不同的数据类型。
2.2、结构体定义和使用
2.2.1、语法:struct 结构体名 { 结构体成员列表 };
2.2.2、通过结构体创建变量的方式有三种:
a)struct 结构体名 变量名;
b)struct 结构体名 变量名 = { 成员1值,成员2值...};
c)定义结构体时顺便创建变量。
2.3、结构体数组
2.3.1、作用:将自定义的结构体放入到数组中方便维护;
2.3.2、语法:struct 结构体名 数组名[ 元素个数 ] = { {},{},...};
#include<iostream>
using namespace std;
struct Student {
string name;
int age;
int score;
};
int main() {
Student stus[3]{
{"张三",18,66},
{"李四",19,70},
{"王五",20,90}
};
for (int i = 0; i < 3; i++) {
cout << "name is " << stus[i].name
<< " age is " << stus[i].age
<< " score is " << stus[i].score << endl;
}
}
2.4、结构体指针
2.4.1、作用:通过指针访问结构体中的成员;
2.4.2、利用操作符 -> 可以通过结构体指针访问结构体属性;
#include<iostream>
using namespace std;
struct student {
string name;
int age;
int score;
};
int main() {
student stu = { "张三",18,98 };
student * p = &stu;
cout << "name is " << p->name << " age is " << p->age << " score is " << p->score << endl;
}