This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug c/49748] New: char * const * cannot be assigned to char const * const *
- From: "gcc at misc dot lka.org.lu" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: Thu, 14 Jul 2011 16:09:11 +0000
- Subject: [Bug c/49748] New: char * const * cannot be assigned to char const * const *
- Auto-submitted: auto-generated
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=49748
Summary: char * const * cannot be assigned to char const *
const *
Product: gcc
Version: 4.4.3
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
AssignedTo: unassigned@gcc.gnu.org
ReportedBy: gcc@misc.lka.org.lu
Trying to assign a pointer value A with type "char * const *" into a variable B
declared as "char const * const * " triggers a warning, although the
const-yness of the type is _increased_ not decreased.
Such a thing may be needed when trying to call a function that displays a list
of strings:
void displayList(char const * const * list)
{
/* display list */
}
The char const * declaration is needed if somewhere in the program, this
function is called with an array of static strings:
char const *list1[] = { "hello", "world", NULL };
displayList(list1);
However, if elsewhere in the program, we want to call the function with a list
of _dynamically_ allocated strings, we get a "initialization from incompatible
pointer type" warning:
char **list2;
for(i=0; i< N; i++)
list2[i] = strdup( some expression );
...
displayList(list2);
for(i=0; i<N; i++)
free(list2[i]);
Because of the free(), we cannot declare list2[] as char const ** , but then
this restriction on _adding_ the const qualifier during assignment or parameter
passing is causing trouble.
There is a very similar case, where such a restriction on adding a const
qualifier makes sense:
assiging char ** to char const **
(i.e. the case where in the target, only the string _contents_ are const, but
not the string pointers themselves).
In this case, the assignment warning would be appropriate, in order to prevent
the following:
char *launderConst(char const *in)
{
char * source[1];
char const ** target = source;
target[0] = in;
return source[0];
}
However if the target list itself is const (rather than just its string
contents), we would never be able to do this:
char const *const* target = source;
target[0] = in;
So why the warning about the first line, if the second one is forbidden anyways
(assigning a value to a const)?
Or is there another way of declaring the displayList() function without
triggering a warning in any of both use-cases?