有什么用const的指针(而不是指向const对象)? [英] What use are const pointers (as opposed to pointers to const objects)?

查看:107
本文介绍了有什么用const的指针(而不是指向const对象)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常用指针const对象,像这样......

I've often used pointers to const objects, like so...

const int *p;

这只是意味着你不能改变的 P 以通过 P 指向整数。但是,我也看到了参考常量指针,声明如下...

That simply means that you can't change the integer that p is pointing at through p. But I've also seen reference to const pointers, declared like this...

int* const p;

据我了解,这意味着,指针变量的本身的是不变的 - 你可以改变它指向整天的整数,但你不能在别的东西使它指向。

As I understand it, that means that the pointer variable itself is constant -- you can change the integer it points at all day long, but you can't make it point at something else.

它会带来什么可能的用途?

What possible use would that have?

推荐答案

当你设计C程序为需要引用相同的内存(多处理器应用程序共享内存)嵌入式系统或特殊用途的程序,那么你需要不断的指针。

When you're designing C programs for embedded systems, or special purpose programs that need to refer to the same memory (multi-processor applications sharing memory) then you need constant pointers.

比如说,我有一个具有的 =HTTP:// flickr.com/photos/adavis/2946164671/\">little LCD 连接到它。我有我的LCD数据写入到内存中的一个特定的端口,然后把它发送到LCD控制器。

For instance, I have a 32 bit MIPs processor that has a little LCD attached to it. I have to write my LCD data to a specific port in memory, which then gets sent to the LCD controller.

我#定义这个数字,但我也有投它作为一个指针,当我做到这一点的C编译器不有尽可能多的选择。

I could #define that number, but then I also have to cast it as a pointer, and the C compiler doesn't have as many options when I do that.

此外,我可能需要它是挥发性的,这也可以投,但它更容易和更清晰的使用所提供的语法 - 一个const指针易失性存储器位置

Further, I might need it to be volatile, which can also be cast, but it's easier and clearer to use the syntax provided - a const pointer to a volatile memory location.

有关电脑程序,一个例子是:如果你设计DOS VGA游戏(有教程在线这是有趣的经历来学习基本的底层图形),那么你需要写的VGA内存,这可能会被引用从一个const指针的偏移量。

For PC programs, an example would be: If you design DOS VGA games (there are tutorials online which are fun to go through to learn basic low level graphics) then you need to write to the VGA memory, which might be referenced as an offset from a const pointer.

这篇关于有什么用const的指针(而不是指向const对象)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆