C 中指针的 const 用法 [英] const usage with pointers in C
问题描述
我正在学习 C 并且有一个关于 const
使用指针的问题.我理解以下代码:
I am going over C and have a question regarding const
usage with pointers. I understand the following code:
const char *someArray
这是定义一个指向 char 类型的指针,const
修饰符意味着存储在 someArray
中的值不能改变.但是,以下是什么意思?
This is defining a pointer that points to types of char and the const
modifier means that the values stored in someArray
cannot be changed. However, what does the following mean?
char * const array
这是指定参数的替代方法,该参数是指向名为array"的数组的字符指针,该数组是 const
并且无法修改?
Is this an alternate way of specifying a parameter that is a char pointer to an array named "array" that is const
and cannot be modified?
最后,这个组合是什么意思:
Lastly, what does this combination mean:
const char * const s2
作为参考,这些取自第 7 章的 Deitel C 编程书籍,所有这些都用作传递给函数的参数.
For reference, these are taken from the Deitel C programming book in Chapter 7 and all of these are used as parameters passed to functions.
推荐答案
const char*
就像你说的,是一个指向 char 的指针,在那里你不能改变 char 的值(至少不是通过指针(没有将常量丢弃)).
const char*
is, as you said, a pointer to a char, where you can't change the value of the char (at least not through the pointer (without casting the constness away)).
char* const
是一个指向字符的指针,您可以在其中更改字符,但不能使指针指向不同的字符.
char* const
is a pointer to a char, where you can change the char, but you can't make the pointer point to a different char.
const char* const
是一个指向常量 char 的常量指针,即你不能改变指针指向的位置,也不能改变指针的值.
const char* const
is a constant pointer to a constant char, i.e. you can change neither where the pointer points nor the value of the pointee.
这篇关于C 中指针的 const 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!