简体   繁体   English

如何使用[]在C中声明指向const字符数组的Const指针

[英]How to declare Const pointer to const character array in C using []

The const wikipedia article states: const Wikipedia文章指出:

int *ptr; // *ptr is an int value
int const *ptrToConst; // *ptrToConst is a constant (int: integer value)
int * const constPtr; // constPtr is a constant (int *: integer pointer)
int const * const constPtrToConst; // constPtrToConst is a constant (pointer)

and

const int*       ptrToConst;     //identical to: int const *       ptrToConst,
const int* const constPtrToConst;//identical to: int const * const constPtrToConst

Great. 大。

How does this apply if I use [] instead of * to declare an array? 如果我使用[]而不是*来声明数组,这将如何应用? For example, how do I turn the following: 例如,如何更改以下内容:

char s[] = "Hello";

into a "const pointer to const"? 变成“指向const的const指针”?

You don't. 你不知道 First of all s is not a pointer, and because it's not a pointer you already can't change the array to "point" somewhere else. 首先, s不是指针,并且因为它不是指针,所以您已经不能将数组更改为“指向”其他位置。

So all you need is to make the contents of the array constant: 因此,您需要做的就是使数组的内容恒定:

const char s[] = "Hello";

The above will declare s as an array of six constant char elements, and initialize the contents with the string "Hello" . 上面的代码将s声明为六个常量char元素的数组,并使用字符串"Hello"初始化内容。

In C, when a qualifier is added to the array declaration then it qualifies the element type instead of array itself. 在C语言中,将限定符添加到数组声明中后,它将限定元素类型而不是数组本身。 C11 section: §6.7.3/9 C11部分:§6.7.3/ 9

If the specification of an array type includes any type qualifiers, the element type is so- qualified, not the array type.[...] 如果数组类型的规范包括任何类型限定符,则元素类型是合格的,而不是数组类型。[...]

So, it is not possible to declare const array of const data type . 因此,不可能声明const数据类型的const数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM