目录
1.字符指针
#include<stdio.h>
int main()
{
char ch[] = "abcdef";
char* pc = &ch;
printf("%s\n", ch);
printf("%s\n", pc);
}
答案:abcdef
abcdef
#include<stdio.h>
int main()
{
char* ch = "abcdef";//"abcdef"是常量字符串,ch存的是首元素地址
printf("%c\n", *ch);
printf("%s\n", ch);
}
答案:a
abcdef
常量字符串不可被修改,看下面例子:
#include<stdio.h>
int main()
{
char* pc = "abcdef";
*pc = 'w';
printf("%s\n", pc);
}
经典案例分析:
int main()
{
char arr1[] = "abcdef";
char arr2[] = "abcdef";
char* p1 = "abcdef";
char* p2 = "abcdef";
if (arr1 == arr2)
{
printf("hehe\n");
}
else
{
printf("haha\n");
}
if (p1 == p2)
{
printf("hehe\n");
}
else
{
printf("haha\n");
}
}
答案:
haha
hehe
2.指针数组
指针数组指的是一个存放指针的数组。
#include<stdio.h>
int main()
{
int* p1[4];//存放整形指针的数组——指针数组
char* p2[4];//存放字符指针的数组——指针数组
}
用法:
#include<stdio.h>
int main()
{
int arr1[] = { 1,2,3,4,5 };
int arr2[] = { 2,3,4,5,6 };
int arr3[] = { 3,4,5,6,7 };
int* parr[] = { arr1,arr2,arr3 };
int i = 0 , j=0;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 5; j++)
{
printf("%d", *(parr[i]) + j);
}
printf("\n");
}
}
3.数组指针
数组指针是一个指针,用来存放数组的地址。
int main()
{
int* a = NULL;//a是整形指针-指向整形的指针-可以存放整形的地址
char* b = NULL;//b是字符指针-指向字符的指针-可以存放字符的地址
int(*c)[] = NULL;//c是数组指针-指向数组的指针-可以存放数组的地址
return 0;
}
例子:
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int(*p)[10] = &arr;
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", (*p)[i]);
}
}
上面函数也可以写成:
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int(*p)[10] = &arr;
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", *(*p+i));
}
}
*p可以当成数组名arr,而数组名又可以看成首元素地址
数组指针在正常情况下用在二维数组:
看下面例子,写一个可以打印二维数组的函数。
void Printf(int(*pa)[5], int x, int y)
{
int i = 0, j = 0;
for (i = 0; i < y; i++)
{
for (j = 0; j < x; j++)
{
printf("%d ", *((*pa + i) + j));
}
printf("\n");
}
}
int main()
{
int arr[3][5] = { {1,2,3,4,5},{2,3,4,5,6},{4,5,6,7,8} };
int(*pa)[5] = &arr;
Printf(pa, 5, 3);
}
执行结果如下:
4.函数指针
函数指针用来存放函数地址
void(*p)(int,int) = &test;
实例:
int add(int x,int y)
{
printf("%d ", x + y);
}
int main()
{
int (*p)(int,int) = &add;
p(3, 4);
(*p)(3, 4);
(**p)(3, 4);
(***p)(3, 4);
}
看出p *p **p ***p,都是该函数。
5.函数指针数组
用来存放函数指针的数组
int add(int x,int y)
{
printf("%d ", x + y);
}
int test1(int x, int y)
{
printf("%d ", x - y);
}
int test2(int x, int y)
{
printf("%d ", x * y);
}
int main()
{
int (*p1)(int, int) = &add;//函数指针
int (*p2)(int, int) = &test1;//函数指针
int (*p3)(int, int) = &test2;//函数指针
int (*pp[3])(int, int) = { p1,p2,p3 };//函数指针数组
}
6.指向函数指针数组的指针
用来存放函数指针数组的地址
int add(int x,int y)
{
printf("%d ", x + y);
}
int test1(int x, int y)
{
printf("%d ", x - y);
}
int test2(int x, int y)
{
printf("%d ", x * y);
}
int main()
{
int (*p1)(int, int) = &add;//函数指针
int (*p2)(int, int) = &test1;//函数指针
int (*p3)(int, int) = &test2;//函数指针
int (*pp[3])(int, int) = { p1,p2,p3 };//函数指针数组
int(*(*ppp)[3])(int, int) = &pp;//指向函数指针数组的指针
}
后续会对该文章内容进行详细补充