Re: Array of char pointers.

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Barry Schwarz wrote:
On Thu, 17 Apr 2008 09:54:42 -0500, "Ben Voigt [C++ MVP]"
<rbv@xxxxxxxxxxxxx> wrote:

New code should always use const whenever you make a pointer to a
string literal.

Not if his code he contains lines like
char x[] = "abc";
arr[0] = x;

Like I said in the beginning, const is appropriate only if all the
elements of arr always point to non-modifiable data.

That snippet doesn't make a pointer to a string literal. It
initializes an array in writable memory. There's a big difference.

I stand by the correctness and universal applicability of my earlier
rule.

So how does your rule deal with

int main(void)
{
char *arr[] = {"a", "bc", "def", "ghij"};
char var[] = "variable text";
int i;
if (i = function_that_decides_predefined_text_is_inappropriate())
{
if (i > 0)
{
var[7] = 'q';
var[8] = '\0';
}
else
{
var[3] = 'y';
var[4] = '\0';
}
arr[0] = var;
}
for (i = 0; i < 4; i++)
puts(arr[i]);
return 0;
}

By changing the type of arr to:

const char *arr[] = { ... };

Which is as it should be.


My only point is that just because a pointer starts out pointing to a
string literal does not mean it will always point to one.

Then it's a polymorphic pointer. char* is a subtype of const char*, if your
collection can contain either then it should be defined using the supertype
as only the operations allowed on the supertype are safe.



Remove del for email


.



Relevant Pages

  • Re: Need some info on const char **
    ... I feel it's good to label the pointer as const. ... It depends on where you put the 'const'. ... void foo(const char * const * bar) ... the 'bar' points to nor what the result of dereferencing ...
    (comp.lang.c)
  • Re: API : constness ?
    ... >const char *const. ... You can declare a constant pointer (you can't change ... Declaring a parameter "const char *" is ONLY an help ...
    (comp.lang.python)
  • Re: pointers to constant characters and constant pointers to characters
    ... I understand the meaning and usage of pointers to constant characters ... char * const s - s is a const pointer to a char ... const char * const t - t is a const pointer to a const char ...
    (comp.lang.c)
  • Re: 406 Not Acceptable (was Re: "--All You Zombies--" title)
    ... Which gets promoted in expressions to const char *. ... You can, in perfectly legal, conforming code, have a non-const pointer ... not even all of the common parts. ...
    (rec.arts.sf.written)
  • Re: best idiom for freeing items from a list
    ... For two pointer types to be compatible, ... trying to define a generic comparison function, ... int my_intcmp(const int* i1, const int* i2) ...
    (comp.lang.c.moderated)