1:通过指针加减的方式访问数组,代码如下:
首先是加法:
#include<stdio.h>
int main()
{
int arr[] = { 0,1,2,3,4,5,6,7,8,9, };
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
int* p = arr;
for (i = 0; i < sz; i++)
{
printf("%d ", *p);
p = p + 1;
}
return 0;
}
程序运行结果如下:
减法:
#include<stdio.h>
int main()
{
int arr[] = { 0,1,2,3,4,5,6,7,8,9, };
int sz = sizeof(arr) / sizeof(arr[0]);
int i = 0;
int* p = &arr[9];
for (i = 0; i < sz; i++)
{
printf("%d ", *p);
p = p-1;
}
return 0;
}
程序运行结果如下:
2:指针减指针
代码如下:
#include<stdio.h>
int main()
{
int arr[] = { 0,1,2,3,4,5,6,7,8,9 };
int* p1 = &arr[0];
int* p2 = &arr[9];
printf(" %d ", *p2 - *p1);
return 0;
}
运行结果为:
所以,指针减去指针得到的是它们之间的元素个数;
举例:利用指针加减的方式求字符数组的元素个数,代码如下:
#include<stdio.h>
int my_strlen(char* str)
{
char* start = str;
char* end = str;
while (*end != '\0')
{
end++;
}
return end - start;
}
int main()
{
char arr[] = "hello,word";
int x=my_strlen(arr);
printf("%d ", x);
return 0;
}
程序运行结果如下:
3:指针数组:
指针数组是指类型同为指针的数组,代码如下:
int main()
{
int a = 50;
int b = 55;
int c = 65;
int* pa = &a;
int* pb = &b;
int* pc = &c;
int*arr[] = { pa,pb,pc };
int i = 0;
for (i = 0; i < 3; i++)
{
printf("%d ", *(arr[i]));
}
return 0;
}
程序运行结果如下: