指针的运算
1.指针 + - 整数
#include <stdio.h>
#include <stdlib.h>
int main(){
char* p1 = (char*)0x100;
printf("%p\n",p1+1); // 00000101
int* p2 = (int*)0x100;
printf("%p\n", p2 + 1);//00000104
short* p3 = (short*)0x100;
printf("%p\n", p3 + 1);//00000102
double* p4 = (double*)0x100;
printf("%p\n", p4 + 1);//00000108
printf("%p\n", p4 + 2);//00000110 进行的是十六进制的计算
system("pause");
return 0;
}
运行结果:
指针 +1 相当于地址向后跳过一个元素(类型本身大小).(与指针的类型有关)
指针 -1 相当于地址向前跳过一个元素(类型本身大小).(与指针的类型有关)
整理总结:
1.数组作为函数参数时会隐式转化指针.(举例:(查找一个数字)数组在进行调用时)
2.数组名直接打印也会隐式转化成指针.
3.数组名参与运算时也会隐式转化成指针.
#include <stdio.h>
#include <stdlib.h>
int main(){
int arr[] = {1,2,3,4};
int* p = &arr[0];
printf("%p\n",arr);// 数组名直接打印会隐式转化会指针,指向首元素的地址
printf("%p\n", p);
printf("%p\n",p+1); //指针+ 1
system("pause");
return 0;
}
运行结果:
#include <stdio.h>
#include <stdlib.h>
int main(){
int arr[] = {1,2,3,4};
int* p = &arr[0];
printf("%d\n",arr[1]); //2
printf("%d\n", *(p+1));//2
printf("%d\n", *p); //1
printf("%d\n",p[1]); //2 *(p+1)=p[1]
system("pause");
return 0;
}
运行结果:
数组和指针:
1.组在很多时候能隐式转化为指针.
2.数组和指针互不相干,一定要区分开
3.数组下标不能取负数,但是指针在有效范围内是可以的
#include <stdio.h>
#include <stdlib.h>
int main(){
int arr[] = {1,2,3,4};
int* p = &arr[2];
printf("%d\n", *p); // 3
printf("%d\n", *(p-1));// 2
printf("%d\n",p[-1]); // 2
system("pause");
return 0;
}
运行结果:
注意: 指针下表可以取负数,但是一定要注意是在有效的范围内
2.指针 - 指针
指针 - 指针必须满足的条件:
1.两个指针的类型相同.
2.两个指针必须指向同一个连续的内存空间.
#include <stdio.h>
#include <stdlib.h>
int main(){
int arr[4] = { 1, 2, 3, 4 };
int* p1 = &arr[0];
int* p2 = &arr[2];
/*int ret = p2 - p1;
printf("%d\n",ret);*/
printf("%p\n", p1);
printf("%p\n", p2);//地址相差 8个字节
printf("%d\n",*p2 - *p1); // 2
system("pause");
return 0;
}
运行结果:
注意: 指针相减实际上两个指针之间隔了几个元素(与类型有关).
** void* 的特殊性:只知道地址不知道大小,是不能进行指针的+ - **
3.指针的关系运算
= = != 比较指针中存的地址是否一样
< > >= <= 用于比较地址的大小,
当进行比较两个指针的地址大小时,但必须满足2个条件:
1.两个指针的类型必须一样.
2.两个指针必须指向同一个连续的内存空间.
//举例1.
#include <stdio.h>
#include <stdlib.h>
int main(){
char str1[] = "hehe";
char str2 []= "hehe";
if (str1 == str2){ //数组本身不能进行比较大小,但数组名参与运算的时候会隐式转成指针
printf("相等\n");
}
else{
printf("不相等\n");
}
system("pause");
return 0;
}
运行结果:
结果是:不相等 str1和str2等于分别申请了一块内存,因此地址是不一样的
== 比较的是字符串的身份/地址
#include <stdio.h>
#include <stdlib.h>
int main(){
char* str1 = "hehe";
char* str2 = "hehe";
if (str1 == str2){ //数组本身不能进行比较大小,但数组名参与运算的时候会隐式转成指针
printf("相等\n");
}
else{
printf("不相等\n");
}
system("pause");
return 0;
}
运行结果:
结果是:相等 str1和str2指向的是同一块地址
c语言中,比较两个字符串有两种方式:
- = = 比较字符串的地址/身份 (一般 ==都是比较内容的,但在c语言和JAVA语言中除外)
- strcmp 比较字符串的内容,而且也能比较字符串的大小
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char str1[] = "hehe";
char str2 []= "hehe";
//数组本身不能进行比较大小,但数组名参与运算的时候会隐式转成指针
printf("%d\n",strcmp(str1,str2));
system("pause");
return 0;
}
运行结果:
结果是 0
strcmp(str1,str2)
1.如果str1>str2,返回一个大于0的数.
2.如果str1<str2,返回一个小于0的数.
3.如果str1==str2,返回0.