指针

  • 指针概念

指针是个变量,也是一个具有特定含义的数字——表示一个内存的地址(房间号)

指针的大小在32位平台是4个字节,在64位平台是8个字节

  • 指针类型

零号内存(房间号)存在但不可用,用其代表特定的含义——空指针NULL(本质是个宏)

  • 指针运算

   指针和整数相加减时,最终的取值和指针的类型密切相关:

#include <stdio.h>
#include <stdlib.h>

int main(){
	char* p = NULL;
	p += 1;  //+1是指 指针里的房间号跳过了指针指向的房间的大小
	int* a = NULL;
	a += 1;
	printf("p=%p\n", p);
	printf("a=%p\n", a);
	system("pause");
	return 0;
}

解引用:

得知指针的房间号,取出房间中的内容

    指针的类型决定了,对指针解引用的时候有多大的权限(能操作几个字节):

#include <stdio.h>
#include <stdlib.h>

int main(){
	int n = 0x11223344;  //内存存的位44 33 22 11
	//字节序:对于一个整形变量来说
	//            若高位存在低字节的内存上,称为小端序
	//            若高位存在高字节的内存上,称为大端序
	char* p = &n; //只可修改一个字节
	*p = 0x55;
	printf("%x\n",n);
	system("pause");
	return 0;
}

   数组名可以当作指向数组首元素的指针来使用:

#include <stdio.h>
#include <stdlib.h>

int main(){
	int arr[10] = { 0 };
	printf("%p\n", arr);  //把数组名当作指针输出
	printf("%p\n", &arr[0]);  //打印数组首元素的地址
	system("pause");
	return 0;
	}

   数组可隐式退化为指针,指针也可当作数组使用:

#include <stdio.h>
#include <stdlib.h>

int main(){
	int arr[5] = { 1,2,3,4,5 };
	printf("%d\n", arr[2]);  
	int* p = arr;
	//以下两种写法等价
	printf("%d\n", p[2]);
	printf("%d\n", *(p + 2));
	system("pause");
	return 0;
	}

指针减去指针:

考量两个指针间的距离

   两个指针指向同一个数组时,此时做减法才有意义;否则,得到的结果没有意义:

#include <stdio.h>
#include <stdlib.h>

int main(){
	int arr[5] = { 1,2,3,4,5 };
	int* p = arr;
	int* p1 = &arr[4];
	printf("%p\n", p);
	printf("%p\n", p1);
	printf("%d\n", p1-p); //差了4个整形变量
	system("pause");
	return 0;
	}

指针的关系运算:

指针的比较

   经常使用空指针作为一个非法的值:

#include <stdio.h>
#include <stdlib.h>

//查找数字是否存在在数组中
//不存在则返回NULL
int* Find(int arr[], int size, int to_find){
	for (int i = 0; i < size; ++i){
		if (arr[i] == to_find){
			return &arr[i];
		}
	}
	return NULL;
}

int main(){
	int arr[5] = { 1,2,3,4,5 };
	int* p = Find(arr,sizeof(arr)/sizeof(arr[0]),100);
	if (p == NULL){
		printf("没找到100!\n");
	}
	else{
		printf("找到了!地址为%p\n",p);
	}
	system("pause");
	return 0;
	}

   比较指针的大小,看房间号的大小:

#include <stdio.h>
#include <stdlib.h>

int main(){
	int arr[5] = { 9,7,5,3,1};
	int* p = &arr[0];
	int* p1 = &arr[1];
	if (p < p1){
		printf("p<p1\n");
	}
	else{
		printf("p>=p1\n");
	}
	system("pause");
	return 0;
	}

二级指针:

指向指针的指针变量

#include <stdio.h>
#include <stdlib.h>

int main(){
	//表示一/表示二等价
	//表示一
	int n = 100;
	int* p = &n;
	int** pp = &p;
	//表示二
	typedef int* int_ptr;
	int n = 100;
	int_ptr p = &n;
	int_ptr* pp = &p;
	system("pause");
	return 0;
}

指针数组与数组指针:

指针数组,也是一个数组,只不过数组中的元素是指针类型的变量

数组指针,也是一个指针,只不过该指针指向了一个数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值