tags:

views:

1184

answers:

2

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?

+11  A: 

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.

JaredPar
+8  A: 

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, i.e.:

const char* const ptr;

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

Good luck!

Drew

Drew Hall
Thanks, that's helpful. Now I just have to remember what it means when the method is marked as const...
Jack BeNimble