C语言指针大杂烩

By francis_hao Oct 31,2016

指针数组和数组指针

指针数组本身是个数组,数组的内容是指针。形如char *pa[]。由于[]优先级高于*,pa先于[]结合表示pa是一个数组,pa[]再与*结合表示pa[]是指针。比如pa[0]放了一个指针。

数组指针本身是个指针,指针指向的是数组。形如char (*ap)[6]。ap与*结合表示ap是个指针,(*ap)再和[6]结合表示(*ap)是个数组名,含有6个元素,可以把(*ap)[6]想成a[6],那么可以把(*ap)看成数组首地址a,而ap就是指向一个含有6个元素的数组的指针。

#include <stdio.h>
int main(void)
{
    int aa[2][6]={{1,2,3,4,5,6},{7,8,9,10,11,12}};
    int (*pa)[6];
    pa = aa;
    //pa=&aa[0]; /*
这样也是可以的*/
    printf("%d ",*(*pa+1));
    printf("%d ",**(pa+1));
    return 0;
}

 

 

指针常量和常量指针

首先共同点是他俩都是指针,只不过侧重点不同,放在前面的就是侧重的。

指针常量侧重于指针,说明指针本身是一个常量性质的,也就是说指针的值是不能改变的,指针常量的形式如:int *const a; 英语读作a const point to int。const放在谁后面就是修饰谁,说明*是const的,不能被修改,如下所示

#include <stdio.h>
int main(void)
{
    int *const cp;
    int aa;
    cp = &aa; /*
错误的,不能在除初始化处对cp进行赋值 */
    return 0;
}

 

只能在定义处赋初值

#include <stdio.h>
int main(void)
{
    int aa;
    int *const cp = &aa; /*
正确的,只能在此处赋值 */
    return 0;
}

常量指针侧重于常量,说明指针指向的内容是常量,指针本身可以改变但是指向的内容不能改变,形式如:const int *a;或者int const *a; 英语读作a point to const int记住,还是const在谁后面就修饰谁,如果在最前面就后移一位。

#include <stdio.h>
int main(void)
{
    int aa;
    const int *p;
    aa = 1;
    p = &aa;
    aa = 2;
    *p = 3; /*
错误的,不能对*p赋值 */
    return 0;
}

在上例中,并不是说aa所在地址的值不能改变了,只是不能通过指针p进行改变,更多的是向编译器进行的说明。

 

指针函数和函数指针

指针函数本身是个函数,具有一个指针类型的返回值.

函数指针本身是个指针,指向一个函数

函数指针由返回值确定类型,和参数无关,下面两段代码展示了这种特性

#include <stdio.h>
int fun1()
{
    printf("fun1 without parameter but return int ");
    return 0;
}
int fun2(char *a)
{
    printf("fun2 with parameter %s and return int ",a);
    return 0;
}
void fun3(char *a)
{
    printf("fun3 with paramete %s but has no return value ",a);
}
int main(void)
{
    int (*pf)();

    pf=fun1;
    (*pf)();

    pf=fun2;
    (*pf)("sencond");

    pf=fun3;
    (*pf)("third");
    return 0;
}

只与返回值有关

#include <stdio.h>
int fun1()
{
    printf("fun1 without parameter but return int ");
    return 0;
}
int fun2(char *a)
{
    printf("fun2 with parameter %s and return int ",a);
    return 0;
}
void fun3(char *a)
{
    printf("fun3 with paramete %s but has no return value ",a);
}
int main(void)
{
    int (*pf)();/*
可以不考虑形参类型*/
    void (*ff)();

    pf=fun1;
    (*pf)();

    pf=fun2;
    (*pf)("sencond");

    ff=fun3;
    (*ff)("third");
    return 0;
}

 


本文由
刘英皓 创作,采用 知识共享 署名-非商业性使用-相同方式共享 3.0 中国大陆 许可协议进行许可。欢迎转载,请注明出处:
转载自:http://www.cnblogs.com/yinghao1991/p/6017894.html

 

参考

【1】 K&R C程序设计语言

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/yinghao-liu/p/6017894.html