灯火互联
管理员
管理员
  • 注册日期2011-07-27
  • 发帖数41778
  • QQ
  • 火币41290枚
  • 粉丝1086
  • 关注100
  • 终身成就奖
  • 最爱沙发
  • 忠实会员
  • 灌水天才奖
  • 贴图大师奖
  • 原创先锋奖
  • 特殊贡献奖
  • 宣传大使奖
  • 优秀斑竹奖
  • 社区明星
阅读:3441回复:0

C语言:const指针使用技巧之——返回指针的函数

楼主#
更多 发布于:2012-09-06 12:32

引言——
     在C语言中,有些函数回返回指针,即为返回指针的函数。通常情况下函数的实现方不希望函数的调用方修改指针指向的内容。
解决方案——
     在函数返回的时候返回一个指向 const 变量的指针。示例代码如下

[cpp]
#include "stdafx.h"

static const int* testPointerToConstVaribles();

int _tmain(int argc, _TCHAR* argv[])
{
    const int *TestPointer = NULL;

    TestPointer = testPointerToConstVaribles();
    
    return 0;
}

const int* testPointerToConstVaribles()
{
    static int ConstVarible = 100;

    return &ConstVarible;//返回指向const变量指针
}
如果在编码中试着改变指针指向的值就会出错,以下是出错代码
[cpp]
#include "stdafx.h"

static const int* testPointerToConstVaribles();

int _tmain(int argc, _TCHAR* argv[])
{
    const int *TestPointer = NULL;

    TestPointer = testPointerToConstVaribles();
        *TestPointer = 34;//修改指针指向的值,引起编译错误

    return 0;
}

const int* testPointerToConstVaribles()
{
    static int ConstVarible = 100;

    return &ConstVarible;//返回指向const变量指针
}
上面代码在VS 2005 下编译会出现以下错误(错误代码块为 "*TestPointer = 34;//修改指针指向的值,引起编译错误")
" error C3892: 'TestPointer' : you cannot assign to a variable that is const"
总结
通过以上方案可以防止非法修改指针指向的值。


摘自 DriverMonkey的专栏


喜欢0 评分0
游客

返回顶部