1. 主页
  2. 文档
  3. C语言教程
  4. C语言指针
  5. const char *p、char * const p 和 const char * const p 的区别

const char *p、char * const p 和 const char * const p 的区别

当 char、const、*、p 都以不同的排列方式使用时,会产生很多混淆,并且含义会根据放置在哪里而改变。以下文章重点介绍所有这些的区分和使用。 
限定符const可以应用于任何变量的声明,以指定其值不会改变。const 关键字适用于紧邻其左侧的任何内容。如果它的左边没有任何东西,它适用于它右边的任何东西。 

1. const char *ptr :这是一个指向常量字符的指针。您无法更改 ptr 指向的值,但可以更改指针本身。“const char *”是指向 const char 的(非 const)指针。

// C program to illustrate
// char const *p
#include<stdio.h>
#include<stdlib.h>

int main()
{
char a ='A', b ='B';
const char *ptr = &a;

//*ptr = b; illegal statement (assignment of read-only location *ptr)

// ptr can be changed
printf( "value pointed to by ptr: %c\n", *ptr);
ptr = &b;
printf( "value pointed to by ptr: %c\n", *ptr);
}

输出: 

value pointed to by ptr:A
value pointed to by ptr:B

注意:const char *p 和 char const *p之间没有区别,因为两者都是指向 const char 的指针,并且 ‘*'(asterik) 的位置也相同。 
2. char *const ptr :这是一个指向非常量字符的常量指针。您不能更改指针 p,但可以更改 ptr 指向的值。

// C program to illustrate
// char* const p
#include<stdio.h>
#include<stdlib.h>

int main()
{
char a ='A', b ='B';
char *const ptr = &a;
printf( "Value pointed to by ptr: %c\n", *ptr);
printf( "Address ptr is pointing to: %d\n\n", ptr);

//ptr = &b; illegal statement (assignment of read-only variable ptr)

// changing the value at the address ptr is pointing to
*ptr = b;
printf( "Value pointed to by ptr: %c\n", *ptr);
printf( "Address ptr is pointing to: %d\n", ptr);
}

输出: 

Value pointed to by ptr: A
Address ptr is pointing to: -1443150762

Value pointed to by ptr: B
Address ptr is pointing to: -1443150762

注意:指针总是指向同一个地址,只有该位置的值改变了。 

3. const char * const ptr :这是一个指向常量字符的常量指针。您既不能更改 ptr 指向的值,也不能更改指针 ptr。 

// C program to illustrate
//const char * const ptr
#include<stdio.h>
#include<stdlib.h>

int main()
{
char a ='A', b ='B';
const char *const ptr = &a;

printf( "Value pointed to by ptr: %c\n", *ptr);
printf( "Address ptr is pointing to: %d\n\n", ptr);

// ptr = &b; illegal statement (assignment of read-only variable ptr)
// *ptr = b; illegal statement (assignment of read-only location *ptr)

}/* Your code... */

输出: 

Value pointed to by ptr: A
Address ptr is pointing to: -255095482

注意: char const * const ptrconst char *const ptr相同。 

这篇文章对您有用吗?