设为首页 加入收藏

TOP

C语言:const指针使用技巧之――返回指针的函数
2014-11-24 00:04:20 来源: 作者: 【 】 浏览:20
Tags:语言 const 指针 使用技巧 返回 函数

引言——
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的专栏

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇自己动手写Gauss消去法 下一篇Hdu 3033 I love sneakers!(DP_背..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: