Re: Array of char pointers.
- From: "Ben Voigt [C++ MVP]" <rbv@xxxxxxxxxxxxx>
- Date: Mon, 21 Apr 2008 11:11:38 -0500
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
.
- References:
- Array of char pointers.
- From: goodTweetieBird
- Re: Array of char pointers.
- From: Barry Schwarz
- Re: Array of char pointers.
- From: goodTweetieBird
- Re: Array of char pointers.
- From: Barry Schwarz
- Re: Array of char pointers.
- From: Ben Voigt [C++ MVP]
- Re: Array of char pointers.
- From: Barry Schwarz
- Re: Array of char pointers.
- From: Ben Voigt [C++ MVP]
- Re: Array of char pointers.
- From: Barry Schwarz
- Array of char pointers.
- Prev by Date: Re: Distributing msvcrt.dll
- Next by Date: WinHttpOpen while using using a Proxy
- Previous by thread: Re: Array of char pointers.
- Next by thread: Question about heritance and other aspects.
- Index(es):
Relevant Pages
|