本文整理翻译自:Difference between const char *p, char * const p and const char * const p
char
, const
, *
, p
不同排列的使用常使我们困扰,它们的不同排列代表着不同的意思。
限定符const
可以应用于任何变量的声明,使其值不可改变。const
关键字应用于紧邻其左侧的内容。如果它的左边没有任何内容,则适用于右边紧接着的内容。
1 const char *ptr
const char *ptr
: This is a pointer to a constant character.(是一个指向常量字符的指针)。PS:中文中常量指针和指针常量太绕,可以先理解英文。您无法更改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);
}
Output:
value pointed to by ptr:A
value pointed to by ptr:B
Note: const char *p
和char const *p
之间没有区别,因为它们都是指向const char
的指针,并且’*’(星号))的位置也相同。
2 char *const ptr
char *const ptr
: This is a constant pointer to non-constant character.(这是一个指向非常量字符的常量指针)。您不能更改指针p
,但可以更改ptr
指向的值。
char *const ptr
中,根据const应用于紧邻其左侧的内容,此时const直接修饰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);
}
Output:
Value pointed to by ptr: A
Address ptr is pointing to: -1443150762
Value pointed to by ptr: B
Address ptr is pointing to: -1443150762
Note: 指针总是指向同一个地址,只是该地址指向的值改变了。
3 const char * const ptr
const char * const ptr
: This is a constant pointer to constant character.(这是一个指向常量字符的常量指针)。您既不能更改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)
}
Output:
Value pointed to by ptr: A
Address ptr is pointing to: -255095482
NOTE: char const * const ptr
与const char *const ptr
意义一致。
「如果这篇文章对你有用,请随意打赏」
如果这篇文章对你有用,请随意打赏
使用微信扫描二维码完成支付

comments powered by Disqus