有什么区别:

char * const 

and

const char *

当前回答

我记得捷克的一本关于C的书:读声明,你从变量开始向左走。 因此,对于

char * const a;

你可以读成:“a是指向char的常量指针类型的变量”,

char const * a;

你可以读成:“a是一个指向char类型常量变量的指针。我希望这能有所帮助。

奖金:

const char * const a;

您将读取为指向char类型的常量变量的is常量指针。

其他回答

const总是修改在它之前的东西(在它的左边),除非它是类型声明中的第一个东西,在那里它修改在它之后的东西(在它的右边)。

所以这两个是一样的

int const *i1;
const int *i2;

它们定义指向const int类型的指针。你可以改变i1和i2的点,但你不能改变它们的值。

这样的:

int *const i3 = (int*) 0x12345678;

定义一个指向整数的const指针,并将其初始化为指向内存位置12345678。您可以更改地址12345678处的int值,但不能更改i3所指向的地址。

Char * const和const Char *?

指向一个常数值

Const char * p;// value不能更改

指向值的常量指针

Char * const p;//地址不能更改

指向常量值的常量指针

Const char * Const p;//两者都不能改变。

这里是一个详细的解释与代码

/*const char * p;
char * const p; 
const char * const p;*/ // these are the three conditions,

// const char *p;const char * const p; pointer value cannot be changed

// char * const p; pointer address cannot be changed

// const char * const p; both cannot be changed.

#include<stdio.h>

/*int main()
{
    const char * p; // value cannot be changed
    char z;
    //*p = 'c'; // this will not work
    p = &z;
    printf(" %c\n",*p);
    return 0;
}*/

/*int main()
{
    char * const p; // address cannot be changed
    char z;
    *p = 'c'; 
    //p = &z;   // this will not work
    printf(" %c\n",*p);
    return 0;
}*/



/*int main()
{
    const char * const p; // both address and value cannot be changed
    char z;
    *p = 'c'; // this will not work
    p = &z; // this will not work
    printf(" %c\n",*p);
    return 0;
}*/

经验法则:从右向左阅读定义!


Const int *foo;

意思是“foo指向(*)一个不能改变的int (const)”。 对于程序员来说,这意味着“我不会改变foo所指向的值”。

*foo = 123;或者foo[0] = 123;是无效的。 Foo = &bar;是被允许的。


Int *const foo;

意思是“foo不能改变(const)并将(*)指向int”。 对于程序员来说,这意味着“我不会改变foo引用的内存地址”。

*foo = 123;或者foo[0] = 123;是被允许的。 Foo = &bar;是无效的。


Const int * Const foo;

意思是“foo不能改变(const)并将(*)指向一个不能改变的int (const)”。 对于程序员来说,这意味着“我不会改变foo所指向的值,也不会改变foo所指向的地址”。

*foo = 123;或者foo[0] = 123;是无效的。 Foo = &bar;是无效的。

常量指针:在整个程序中,常量指针只能指向相应数据类型的单个变量。我们可以改变指针所指向的变量的值。初始化应该在声明本身的时候进行。

语法:

datatype *const var;

Char *const属于这种情况。

/*program to illustrate the behaviour of constant pointer */

#include<stdio.h>
int main(){
  int a=10;
  int *const ptr=&a;
  *ptr=100;/* we can change the value of object but we cannot point it to another variable.suppose another variable int b=20; and ptr=&b; gives you error*/
  printf("%d",*ptr);
  return 0;
}

指向const值的指针:在这种情况下,指针可以指向任意数量的相应类型的变量,但不能改变指针在特定时间所指向的对象的值。

语法:

Const *var数据类型

Const char*属于这种情况。

/* program to illustrate the behavior of pointer to a constant*/

   #include<stdio.h>
   int main(){
       int a=10,b=20;
       int const *ptr=&a;
       printf("%d\n",*ptr);
       /*  *ptr=100 is not possible i.e we cannot change the value of the object pointed by the pointer*/
       ptr=&b;
       printf("%d",*ptr);
       /*we can point it to another object*/
       return 0;
    }