当前位置:网站首页>三.两数交换 空指针 && 野指针 解引用问题
三.两数交换 空指针 && 野指针 解引用问题
2022-08-09 15:07:00 【榶曲】
目录
在做两数交换时,使用指针来接收需要交换的数是什么情况?以下是我的一些实验结论
正常交换
void swap(int* x, int* y)
{
int temp = 0;
temp = *x;//*x为指针x的解引用操作,表示a的值
*x = *y;
*y = temp;
}
int main()
{
int a = 0;
int b = 0;
scanf("%d %d", &a, &b);
printf("交换前a=%d,b=%d\n", a, b);
swap(&a, &b);
printf("交换后a=%d,b=%d\n", a, b);
return 0;
}空指针
情况一:
void swop(int* x, int* y)
{
int* temp = NULL;
*temp = *x;//*x为指针x的解引用操作,表示a的值
*x = *y;
*y = *temp;
}
int main()
{
int a = 0;
int b = 0;
scanf("%d %d", &a, &b);
printf("交换前:a=%d,b=%d\n", a, b);
swop(&a, &b);
printf("交换后:a=%d,b=%d\n", a, b);
return 0;
}
temp为空指针,空指针执向0地址,该指针为空,是无效的,不能对无效的指针解引用
当它发生解引用时,会发生指针解引用错误。
情况二:
void swop(int* x, int* y)
{
int* temp = NULL;
temp = *x;
//在c语言的语法上这种写法是不正确的
//但是在指针变量解引用后,看做一个整形变量放到temp指针中是可以放下的
*x = *y;
*y = temp;
}
野指针
情况一:
void swop(int* x, int* y)
{
int* temp;
*temp = *x;
*x = *y;
*y = *temp;
}
系统直接崩溃,因为temp为野指针
野指针,即未初始化的指针,没有访问权限的地址(指针)
情况二:
void swop(int* x, int* y)
{
int* temp;
temp = *x;
//在c语言的语法上这种写法是不正确的
//但是在指针变量解引用后,看做一个整形变量放到temp指针中是可以放下的
*x = *y;
*y = temp;
}
边栏推荐
猜你喜欢
随机推荐
线性表重点之链表
学习编程的第四天
4. Using Local Geospatial Data
学编程的第六天
C语言三大循环while,for,do...while
2022国赛数学建模思路汇总A题B题C题D题 高教社杯
Anatomy of Storage Size, Value Range, and Output Format of Basic Data Types in C Language
经典题型(一)
微服务框架笔记(1)
设计一个登录小程序(while和getchar实现)
C语言分支语句if,switch语句详细讲解
float属性的使用
2022华数杯B题思路: 水下机器人的组装计划
MYSQL数据库一周基础入门(第二天)
2021深圳杯A题思路 火星探测器着陆控制方案
0. About The Author And Preface
IDEA中操作数据库 以MySQL为例,可以放弃Navicat了
Lens 创建 Service Accounts 及分配权限
Tracert 命令穿越防火墙不显示星号*的方法
Go语言基础(十一):反射









