常量指针与常量值上的指针 [英] constant pointer vs pointer on a constant value

查看:34
本文介绍了常量指针与常量值上的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下声明有什么区别?

char * const a;
const char * a;

为了理解区别我写了这个小程序:

In order to understand the difference I wrote this small program:

#include <stdio.h>
#include <stdlib.h>


int main (int argc, char **argv)
{
    char a = 'x';
    char b = 'y';

    char * const pc1 = &a;
    const char * pc2 = &a;

    printf ("Before
");
    printf ("pc1=%p
", pc1);
    printf ("*pc1=%c
", *pc1);
    printf ("pc2=%p
", pc2);
    printf ("*pc2=%c
", *pc2);

    *pc1 = b;
/*     pc1 = &b; */

/*     *pc2 = b; */
    pc2 = &b;

    printf ("

");

    printf ("After
");
    printf ("pc1=%p
", pc1);
    printf ("*pc1=%c
", *pc1);
    printf ("pc2=%p
", pc2);
    printf ("*pc2=%c
", *pc2);

    return EXIT_SUCCESS;
}

我编译了程序(使用 gcc 3.4)并运行它.输出很好地突出了差异:

I compiled the program (with gcc 3.4) and ran it. The output highlights the difference rather well:

Before
pc1=ffbfd7e7
*pc1=x
pc2=ffbfd7e7
*pc2=x


After
pc1=ffbfd7e7
*pc1=y
pc2=ffbfd7e6
*pc2=x

然而,我不得不编写小程序才能得到答案.如果我不在机器旁边(例如在面试时),我将无法回答这个问题.

However, I had to write the small program to get the answer. In case I'm away from the machine (at an interview for instance), I wouldn't be able to answer the question.

有人可以通过评论上面的例子来解释 const 关键字是如何运作的吗?

Can someone please explain, by commenting the above example, how the const keyword operates?

推荐答案

char * const a;

表示指针是常量和不可变的,但指向的数据不是.
在这种情况下,您可以使用 const_cast(在 C++ 中)或 c-style cast 来丢弃常量,因为数据本身不是常量.

means that the pointer is constant and immutable but the pointed data is not.
You could use const_cast(in C++) or c-style cast to cast away the constness in this case as data itself is not constant.

const char * a;

表示不能使用指针 a 写入指向的数据.在这种情况下,使用 const_cast(C++) 或 c 风格的强制转换来丢弃常量会导致 未定义行为.

means that the pointed data cannot be written to using the pointer a. Using a const_cast(C++) or c-style cast to cast away the constness in this case causes Undefined Behavior.

这篇关于常量指针与常量值上的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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