#include <stdio.h>
/*
指针:就是地址
&变量名:获取改变量的地址,"&"取地址符
int *p;定义一个整型指针(地址)变量
*p:解引用,间接访问符
指针的大小: 在32位平台(win32,x86)4字节;在64位平台(x64,arm64)8字节 考试重点
结论:一个函数想要修改另一个函数的变量值,必须传指针和解引用. 非常重要
数组和指针的转换
*(arr+i) == arr[i]
p[i] == *(p+i) 建议:数组或者指向数组开头的指针,都通过下标访问更好理解
*/
//野指针:悬挂指针,没有访问权限的地址
int main()
{
int *p = (int *)2000;//野指针
//printf("%d\n",p+1);//
*p = 50;//崩溃
printf("%d\n",*p);
return 0;
}
/*
void Fun(int **p)
{
//p = NULL;
*p = NULL;
}
//用二级指针
//NULL:空指针,无效指针,不能解引用
int main()
{
int a = 10;
int *p = &a;
//p = NULL;
Fun(&p);
printf("%d\n",*p);//1.为什么不崩溃,2,怎么改
return 0;
}
*/
/*
int main()
{
//int a;
//scanf("%d",&a);
int arr[10] = {1,2,3,4,5,6,7};
int *p = arr;
printf("%d,%d\n",arr[3],*(arr+3));
printf("%d,%d\n",p[3],*(p+3));
p = &arr[3];
printf("%d\n",p[-1]);//*(p-1)
return 0;
}
*/
/*
//交换两个数的值
void Swap_err1(int a,int b)//没有传指针,只是值传递
{
int tmp = a;
a = b;
b = tmp;
}
void Swap_err2(int *p1,int *p2)//没有解引用
{
int *tmp = p1;
p1 = p2;
p2 = tmp;
}
void Swap_err3(int *p1,int *p2)//野指针
{
int *tmp;//野指针
*tmp = *p1;//崩溃
*p1 = *p2;
*p2 = *tmp;
}
void Swap(int *p1,int *p2)
{
int tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
int main()
{
int a = 10;
int b = 20;
Swap(&a,&b);
printf("%d,%d\n",a,b);
int *p = NULL;//
return 0;
}
*/
/*
//指针大小
int main()
{
printf("%d\n",sizeof(char *));
printf("%d\n",sizeof(short *));
printf("%d\n",sizeof(int *));
printf("%d\n",sizeof(long long *));
printf("%d\n",sizeof(double *));
printf("%d\n",sizeof(char ****));
return 0;
}
*/
//数组和指针的转换
//*(arr+i) == arr[i]
//p[i] == *(p+i) 建议:数组或者指向数组开头的指针,都通过下标访问更好理解
/*
int main()
{
int a = 10;
int b = 20;
int *p = &a;
*p = 100;//a = 100;
p = &b;
*p = 200;//b = 200;
&p;//int a,&a->int * ;int *p,&p->int * *
int **pp = &p;
*pp = &a;//p = &a;
**pp = 1000;//a = 1000;
*pp = &b;
**pp = 2000;
return 0;
}
*/
指针
最新推荐文章于 2023-10-10 10:43:34 发布
本文详细介绍了C语言中的指针概念,包括如何获取变量地址、如何定义和使用指针,以及指针在函数参数传递中的作用。讨论了野指针、数组与指针的转换、指针大小和指针运算。还通过示例展示了如何正确地交换两个变量的值,以及如何避免常见的指针错误。
摘要由CSDN通过智能技术生成