简体   繁体   English

指针和const char []导致C错误

[英]C error with pointer and const char[]

I have a const char arr[] parameter that I am trying to iterate over, 我有一个const char arr []参数,我想对其进行迭代,

char *ptr;
for (ptr= arr; *ptr!= '\0'; ptr++) 
  /* some code*/

I get an error: assignment discards qualifiers from pointer target type 我收到一个错误:分配从指针目标类型中丢弃了限定词

Are const char [] handled differently than non-const? const char []与非const的处理方式不同吗?

Switch the declaration of *ptr to be. 将* ptr的声明切换为。

const char* ptr;

The problem is you are essentially assigning a const char* to a char*. 问题是您实际上是将const char *分配给char *。 This is a violation of const since you're going from a const to a non-const. 因为您要从const变为非const,所以这违反了const。

As JaredPar said, change ptr's declaration to 正如JaredPar所说,将ptr的声明更改为

const char* ptr;

And it should work. 它应该工作。 Although it looks surprising (how can you iterate a const pointer?), you're actually saying the pointed-to character is const, not the pointer itself. 尽管看起来很令人惊讶(如何迭代const指针?),但实际上您是在指出指向的字符是const,而不是指针本身。 In fact, there are two different places you can apply const (and/or volatile) in a pointer declaration, with each of the 4 permutations having a slightly different meaning. 实际上,可以在指针声明中应用const(和/或volatile)有两个不同的地方,这4个置换中的每一个含义都稍有不同。 Here are the options: 以下是选项:

char* ptr;              // Both pointer & pointed-to value are non-const
const char* ptr;        // Pointed-to value is const, pointer is non-const 
char* const ptr;        // Pointed-to value is non-const, pointer is const
const char* const ptr;  // Both pointer & pointed-to value are const.

Somebody (I think Scott Meyers) said you should read pointer declarations inside out, ie: 有人(我认为Scott Meyers)说过,您应该由内而外读取指针声明,即:

const char* const ptr;

...would be read as "ptr is a constant pointer to a character that is constant". ...将被解读为“ ptr是指向常量字符的常量指针”。

Good luck! 祝好运!

Drew 德鲁

The const declaration grabs whatever is to the left. const声明获取左侧的所有内容。 If there is nothing it looks right. 如果什么也没有,那么看起来不错。

For interation loops like the above where you don't care about the value returned you should say ++ptr rather than ptr++ . 对于像上面这样的交互循环,您不关心返回的值,应该说++ptr而不是ptr++

ptr++ means: ptr++意思是:

temp = *ptr;
++ptr;
return temp;`

++ptr means: ++ptr意思是:

++ptr;
return *ptr;

For the primitive types, the compiler will apply this optimization but won't when iterating over C++ objects so you should get in the habit of writing it the right way. 对于原始类型,编译器将应用此优化,但在C ++对象上进行迭代时则不会应用此优化,因此您应养成以正确方式编写它的习惯。

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

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