函数指针:
指向函数的指针;格式:
类型说明符(*指针变量名)()
#include <stdio.h>
void print()
{
printf("helloworld\n");
}
int add(int x, int y)
{
return (x + y);
}
int main()
{
void (*p)(); //函数指针 指向一个没有形参、没有返回值的函数
p = print;
p();
int (*q)(int, int);//int,int是参数的类型
q = add;
q(1, 2);
return 0;
}
指针函数:
返回值是指针的函数
格式:类型说明符 *函数名(形参)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *Init() //指针函数
{
char *tmp = (char *)malloc(sizeof(char) * 10);
return tmp;
}
int main()
{
char *str;
str = Init();
strcpy(str, "hello");
return 0;
}
数组指针 :
int (*a)[ ];
数组指针可以类比二维数组来理解:
a[0]=*(a+0)=*a //"="是相等的意思不是c语言中的赋值符号,都表示第0行第0列元素的地址
a+1=&a[1] //第一行的首地址,要打印第一行的元素直接pfintf("%d",a[1]);
//用数组指针实现多个字符串的遍历输出
#include <stdio.h>
int main()
{
char a[3][64] = {"helloworld","hello china","I love chinse food"};
char (*p)[64] = a;
int i;
for(i = 0; i < 3; i++)
{
printf("%s\n",p[i]);
}
return 0;
}
指针的指针:
#inlcude <stdio.h>
#include <string.h>
#include <stdlib.h>
void add(char **str)
{
*str = (char *)malloc(sizeof(char) * 64);
}
int main()
{
char *ptr = NULL; //定义一个空指针
add(&ptr);
strcpy(ptr,"helloworld");
printf("%s",ptr);
return 0;
}
将指针ptr的地址作为实参 传给add, 因为传输数据是指针的地址,所以子函数的形参就需要定义一个char **类型的指针来接受传输的数据,str存放的就是指针ptr的地址,*str = (char *)malloc(sizeof(char) * 64);就是给ptr开辟长度为64位的内存空间,那么就可以在内存空间中写入数据。