简体   繁体   中英

C error with pointer and const char[]

I have a const char arr[] parameter that I am trying to iterate over,

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?

Switch the declaration of *ptr to be.

const char* ptr;

The problem is you are essentially assigning a const char* to a char*. This is a violation of const since you're going from a const to a non-const.

As JaredPar said, change ptr's declaration to

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. 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. 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:

const char* const ptr;

...would be read as "ptr is a constant pointer to a character that is constant".

Good luck!

Drew

The const declaration grabs whatever is to the left. 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++ means:

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

++ptr means:

++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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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