刚才对C语言指针进行了全面的学习,看了不少资料,学到了不少东西。
记得大一下学期就学了C语言了,当初老师只教了些基本的东西,后来讲指针只是带过了,以没时间为由结束了C的学习,这个后来的C数据结构的学习带来了问题。没有学好C指针,数据机构的例子也就很难看懂,这更加大了学习数据结构的难度。还是由于老师的关系(数据结构的老师也就是C语言老师),很大原因是老师的普通话太差劲了,听起课来特别费力,这大大打击了我学习数据结构这门课的热情。
今天,我准备参加ACM比赛,虽然我的数据结构不怎么样,C语言也很一般,但是我还是参加了,这是一次难得的机会,对于快要结束四年大学生活的我来说,是时候在大学的时候留下点什么了。
过去的找不回来了,只能用现在的努力来弥补。说了这么多,还是回到正题吧。
众所周知,指针是用来指向内存地址的变量,而所有的变量在内存中都分配有一定的空间,每个内存空间都有自己的地址。正由于这个特性,所以指针可以做很多事。如:
1.指向某个变量的。
2.作为参数,可以改变全局变量的值,也叫变参。
3.函数指针,感觉有点像C++ 的模板函数,但又不是。
……
具体举例:
1. Example:
int * p;
int a=9;
p=&a;
printf("Result: %d /n",*p);
Ouput:Result: 9
2.Example:
In C:
// Takes the value of interest by reference and adds 2.
void C(int* worthRef) {
*worthRef = *worthRef + 2;
}
// Adds 1 to the value of interest, and calls C().
void B(int* worthRef) {
*worthRef = *worthRef + 1; // add 1 to value of interest as before
C(worthRef); // NOTE no & required. We already have
// a pointer to the value of interest, so
// it can be passed through directly.
}But in C++ is:
void Swap(int& a, int& b) { // The & declares pass by reference
int temp;
temp = a; // No *'s required -- the compiler takes care of it
a = b;
b = temp;
}
void SwapCaller() {
int x = 1;
int y = 2;
Swap(x, y); // No &'s required -- the compiler takes care of it
}注意变参 int* a和int& a,效果是一样的,但在C中int& a是编译不通过的。
3.Example:
一个很好的例子:
//自行包含头文件
void CallMyFun(FunType fp,int x) //③. 参数fp的类型是FunType。
{
fp(x);//④. 通过fp的指针执行传递进来的函数,注意fp所指的函数是有一个参数的
}
void MyFun1(int x) // ①. 这是个有一个参数的函数,以下两个函数也相同
{
printf(“函数MyFun1中输出:%d/n”,x);
}
void MyFun2(int x)
{
printf(“函数MyFun2中输出:%d/n”,x);
}
void MyFun3(int x)
{
printf(“函数MyFun3中输出:%d/n”,x);
}
typedef void (*FunType)(int ); //②. 定义一个函数指针类型FunType,与①函数类型一至
void CallMyFun(FunType fp,int x);
int main(int argc, char* argv[])
{
CallMyFun(MyFun1,10); //⑤. 通过CallMyFun函数分别调用三个不同的函数
CallMyFun(MyFun2,20);
CallMyFun(MyFun3,30);
}
//-----------------------------------------------------------------
自己理解:
声明函数类型指针:int (*FunName)(int[,int]...);
数据结构中遍历的例子:
Status PreOrderTravel(LinkList *L,ElementType e,Status (*View)(ElementType))
{
表达式……
……
View(e);
……
}
这里的Status(*View)(ElementType)就是一个函数指针。
使用这个函数之前必须对他进行定义:Status printTravel(ElementType e){printf(" %d /n",e);return OK;}
直到现在我们才可以调用函数PreOrderTravel(LinkList *L,ElementType e,Status (*View)(ElementType));
应该这样调用他:PreOrderTravel(&L,e,printTravel);//printTravel这里将函数地址传给PreOrderTravel函数中的View函数。
That's all,thank you ! Power By LongLongAgo