先决条件:指针
当char, const, *, p都用在不同的排列中时, 含义会根据放置在何处而变化, 这会引起很多混乱。下一篇文章重点介绍所有这些的区别和用法。
预选赛const可以应用于任何变量的声明以指定其值不会更改。 const关键字适用于左侧的任何内容。如果左侧没有任何内容, 则适用于右侧的任何内容。
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)的位置也相同。
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
注意:指针始终指向相同的地址, 仅更改该位置的值。
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)
}
输出如下:
Value pointed to by ptr: A
Address ptr is pointing to: -255095482
注意:char const * const ptr与…相同const char * const ptr.
const关键字测验
如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。