常量指针VS指针上一个恒定值 [英] constant pointer vs pointer on a constant value

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

问题描述

什么是下面的声明之间的区别?

  char * const的一个;
为const char * A;

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

 的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
INT主(INT ARGC,字符** argv的)
{
    所以char a ='X';
    焦炭B ='Y';    char * const的PC1 =安培; A;
    为const char * PC2 =安培; A;    的printf(\\ n之前);
    的printf(PC1 =%P \\ N,PC1);
    的printf(* PC1 =%C \\ n,* PC1);
    的printf(PC2 =%P \\ N,PC2);
    的printf(* PC2 =%C \\ n,* PC1);    * PC1 = B;
/ * = PC1和b; * // * * PC2 = B; * /
    PC2 =和b;    的printf(\\ n \\ n);    的printf(\\ n后);
    的printf(PC1 =%P \\ N,PC1);
    的printf(* PC1 =%C \\ n,* PC1);
    的printf(PC2 =%P \\ N,PC2);
    的printf(* PC2 =%C \\ n,* PC1);    返回EXIT_SUCCESS;
}

我编译的程序(用gcc 3.4)并运行它。输出凸显差异相当好:

 之前
PC1 = ffbfd7e7
* PC1 = X
PC2 = ffbfd7e7
* PC2 = X

PC1 = ffbfd7e7
* PC1 = Y
PC2 = ffbfd7e6
* PC2 = Y

不过,我不得不写小程序来得到答案。如果我是从机器(在例如接受采访)走,我不能回答这个问题。

有人可以解释,通过注释上面的例子,如何使用常量关键字操作?


解决方案

  char * const的一个;

意味着该指针是恒定的并且不可改变的但尖的数据是没有的。结果,
你可以使用的const_cast (在C ++)或C样式转换为抛弃常量性在这种情况下,作为数据本身不是恒定的。

 为const char * A;

意味着尖数据不能被写入到使用指针。
使用的const_cast (C ++)或C样式转换为抛弃常量性在这种情况下导致的未定义行为

What is the difference between the following declarations?

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\n");
    printf ("pc1=%p\n", pc1);
    printf ("*pc1=%c\n", *pc1);
    printf ("pc2=%p\n", pc2);
    printf ("*pc2=%c\n", *pc1);

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

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

    printf ("\n\n");

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

    return EXIT_SUCCESS;
}

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=y

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.

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

解决方案

char * const a;

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;

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.

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

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