C语言指针使用小记 (深入理解C指针 读后小记)

最近正值过年在家,新年初一,闲暇时间无事可做便把以前看过的书籍整理了一下,顺手也把这本“深入理解C指针”的书重新读了一遍,这本书总体感觉比较简单,但是还是不免有些地方是平时没有想到过或者没有注意到的,这里做下记录以便以后需要时再来查看。

 

1.  自实现   内存 安全释放函数   safeFree

  

对空地址释放内存 或者 对已经释放内存的 地址释放内存, 报错。

自实现   内存 安全释放函数:

void  safeFree(void **pp)
{
    if(pp!==NULL && *pp!=NULL)
    {
        free(*pp);
        *pp=NULL;
    }
}

 

具体:

加入宏定义, 函数调用时不需要显示做类型转换  宏定义的前后两个函数名不能相同,宏定义只是简单的文本替换的预编译

#include <iostream>
#include <malloc.h>
using namespace std;
#define safeFree(p) safeFree_2((void **)&(p))
void safeFree_2(void **p)
{
    if(p!=NULL && *p!=NULL)
    {
        free(*p);
        *p=NULL;
    }
}

int main()
{
int *p, **q;
p=(int *)malloc(sizeof(int));
safeFree(p);
safeFree(p);
p=(int *)malloc(sizeof(int));
q=&p;
safeFree(*q);
safeFree(*q);
return 0;
}

 

 

2.  指针数组    和    数组指针

 

 

3.  函数指针 数组

因为函数的地址可以作为函数指针进行传递, 但是函数本身不可以作为参数传递,所以只存在 函数指针数组 不存在  (数组函数 指针)

 

第一种形式:
typedef int(*operation)(int, int); operation operations[128]={NULL};

第二种形式:
int (*operations[128])(int, int)={NULL};

 

 

 

 

#include <iostream>
using namespace std;
typedef int (*fptr)(int, int);
int (*operations[128])(int, int)={NULL};

int add(int x, int y)
{
    return x+y;
}
int substract(int x, int y)
{
    return x-y;
}
void initializeOperationsArray()
{
    operations['+']=add;
    operations['-']=sub;
}

int evaluateArray(char opcode, int num1, int num2)
{
    fptr operation;
    operation=operations[opcode];
    return operation(num1, num2);
}

int main()
{
    initializeOperationsArray();
    cout<<evaluateArray('+', 30, 20)<<endl;
    cout<<evaluateArray('-', 30, 20)<<endl;
    return 0;
}

 

 

 

 

 

4.  函数指针 的 互换

 

typedef int (*fptrToSingleInt)(int);
typedef int (*fptrToTwoInts)(int, int);
int add(int, int);


fptrToTwoInts fptrFirst=add;
fptrToSingleInt fptrSecond = (fptrSingleInt)fptrFirst;
fptrFirst = (fptrToTwoInts)fptrSecond;

 

函数指针类型转换 可能会改变指针长度 或 出错, 不过一般情况下会给出正确结果。(C/C++多标准,不同厂商,编译环境所决定)

同时,无法保证 函数指针 和 数据指针 相互转换后正常工作,如:

void *pv=add;

 

一般情况下进行函数指针交换 可以采用基本函数指针类型。

typedef void(*fptrBase)();

 

fptrBase basePointer;
fptrFirst=add;

basePointer=(fptrToSingleInt)fptrFirst;
fptrFirst=(fptrToTwoInts) basePointer;

 

posted on 2017-01-28 09:36  Angry_Panda  阅读(604)  评论(0编辑  收藏  举报

导航