指针 基本概念
地址类型变量
大小 x86 32位
sizeof(long long*) 4 8
0x0000 0000~0xffff ffff
0000 0000 1111 1111(无符号)
int*p=&a p指针指向a
p指针保存a地址
int **q=&p 二级指针
*q 解引用
(1)指针定义
1.普通指针
int val=0;
int *p=&val;
2.数组指针
int arr[3];
int (*p1)[3]=&arr;
p1 +1 能力偏移量12个字节
重命名
typedef int *Pint;
typedef int (*PARR) [3];
3.函数指针
int add(int a,int b);
int (*p)(int ,int)=add;
add(1,2);
p(1,2);
函数指针声明
typedef int (*PFun)(int ,int);
PFun p=add;
p(1,2); //add(1,2);
(2)普通指针使用
1.字符数组,查找是否存在元素‘a’ (指针)
#include <stdio.h>
#include <string.h>
bool Search(char* arr, char c,int len) {
char* a = arr;
for (a; (int)a < len;a++) {
if (*a == c)
return true;
}
return false;
}
int main() {
char arr[] = "wkendwjab574545c";
int len = strlen(arr);
char c = 'a';
bool re = Search(arr, c,len);
printf("%d", re);
return 0;
}
2. char*q=(char*)p;
*q=66;
指针验证法
int val=0x12345678;
char*p=(char*)&val;
if(*p==0x78){小端}
else {大端}
3.mystrcpy() 使用指针 遍历
#include <stdio.h>
#include <string.h>
void mystrcpy(char* str, char* sub,int len) {
char* p = str;
char* q = sub;
for (int i = 0; i < len; i++) {
*q = *p;
q++;
p++;
}
}
int main() {
char str[] = "sjdwjnecw incw";
int len = strlen(str);
char sub[100];
mystrcpy(str, sub,len);
for (int i = 0; i < len; i++) {
printf("%c", sub[i]);
}
return 0;
}
4.
(3)判断大小端问题
折半查找(二分查找)
前提 :数组 有序 assert 运用 断言
#include <stdio.h>
#include <string.h>
#include <assert.h>
int BinarrySearch(int* arr, int c,int len) {
assert(arr != NULL); //断言,对函数运行设立条件 arr=NULL 断言失败 ,后续代码不执行
if (len < 0) return 0; //数组长度 大于等于0
for (int i = 0, j = len; j <= i;) {
int m = (i + j) / 2;
if (c > arr[m]) {
i = m+1;
}
if (c < arr[m]){
j = m-1;
}
if (arr[m] == c) {
return 1;
}
return 0;
}
}
int main() {
int arr[] = { 1,4,7,9,13,15,16 };
int c = 13;
int len = sizeof(arr) / sizeof(arr[0]);
int X = BinarrySearch(arr, c,len);
if (!X) printf("找到");
else printf("未找到");
return 0;
}
(4)指针+1 能力
指针变量加1,即向后移动1 个位置表示指针变量指向下一个数据元素的首地址。而不是在原地址基础上加1。至于真实的地址加了多少,要看原来指针指向的数据类型是什么。
指针+1
int arr[]={1,2,3,4,5,6,7};
int *p=arr; &arr[0]
*p=6; 第一个数变为6
p+1 ==>p的偏移量+sizeof(类型)字节
数组与指针 arr[0] ==> *(arr+0)
(5)指针数组
char * arr[3]={"abc","hello","word"};
0x12 |
0xab |
0xdf |
0x12 |
"abc" | |
0xab |
"hello" | |
0xdf |
"word" |
(6)const 与指针结合
const int *p =&val; 不能通过p修改p所指之物
int * const p=&a; p本身常性
const int * const p=&a;
#include <stdio.h>
int main() {
char a = 'w';
char b = 'e';
char* p = &a;
char** q = &p;
const char c = 'a';
const char* s = &c;
const char** t = &s;
char d = 'd';
const char* pd = &d;
char* const ps = &d;
const char** w = &pd;
const char** w = &pd;
char* const *r = &ps;
return 0;
}