const限定符和Const指针

时间:2014-10-02 10:13:37

标签: c pointers const

我总是在const指针中混淆。 任何人都可以用简单的方式解释我的内容如下 代码片段试图说。我知道他们在说什么,但我需要理由 以简单的方式。谢谢

    char *p="Hello";                 /*pointer is variable,so string is*/
    *p='M';
    p="BYE";       /*works*/
    p="Bye";      /*works*/

    const char *q="Hello";            /*string is constant pointer is not */
   *q='M';       /*Error*/
    q="BYE";      /*works*/

   char const *s="Hello";           /*string is constant pointer is not */
   *s='M';      /*Error*/
   s="BYE";    /*works*/

   char* const t="Hello";          /*pointer is constant string is not */
   *t='M';     /*works*/
   t="BYE";   /*error*/

   const char* const u="Hello";   /*string is constant,so is pointer*/
   *u='M';    /*error*/
   u="BYE";  /*error*/

1 个答案:

答案 0 :(得分:0)

实际上这三个代码段

    char *p="Hello";                 /*pointer is variable,so string is*/
    *p='M';
    p="BYE";       /*works*/
    p="Bye";      /*works*/

    const char *q="Hello";            /*string is constant pointer is not */
   *q='M';       /*Error*/
    q="BYE";      /*works*/

   char const *s="Hello";           /*string is constant pointer is not */
   *s='M';      /*Error*/
   s="BYE";    /*works*/

在某种意义上是等效的,你可能不会改变指针所指向的对象。区别在于将限定符const添加到q的定义允许编译器在编译时找到错误。

您不能修改字符串文字。任何修改字符串文字的尝试都会导致程序的未定义行为。在C字符串中,文字具有非const字符数组的类型。但是,在第二个代码片段中添加限定符const允许编译器在编译时找到错误。

C标准(6.4.5字符串文字)

  

7未指明这些阵列是否与它们不同   元素具有适当的值。 如果程序尝试   修改这样的数组,行为是未定义的。

除了记录之间的审美之外没有区别

const char *

char const *

两者都定义了指向常量对象的指针。指针本身并不是一成不变的。

但是如果你要写下面的方式

char s[] ="Hello";                 /*pointer is variable,so string is*/
char *p = s;
const char *q = s;
*p='M';
*q='M';

然后使用带或不带const限定符的指针之间存在差异,因为您可能会更改字符数组。对于最后一个语句,编译器将发出错误。

最后两个代码片段与前三个代码片段的不同之处在于,后两个定义的常量指针可能不会更改指针的值。然后你试图重新分配编译器发出错误的常量指针。常量对象在定义时应初始化。

相关问题