吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → const char *p、char * const p 和 const char * const p 的区别

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

来源:网络 | 更新时间:2022-01-18 19:49:54
当 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: %cn", *ptr);
ptr = &b;
printf( "value pointed to by ptr: %cn", *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: %cn", *ptr);
printf( "Address ptr is pointing to: %dnn", 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: %cn", *ptr);
printf( "Address ptr is pointing to: %dn", 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: %cn", *ptr);
printf( "Address ptr is pointing to: %dnn", 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相同。 

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com