In C, I try to implement a dynamic array of strings (much like the C++ std::vector<std::string>) with inspiration from https://stackoverflow.com/a/3536261/2690527.
Currently my code looks like
string_array.h:
#ifndef _STRING_ARRAY_H_
#define _STRING_ARRAY_H_
struct string_array_t;
struct string_array_t* create_string_array( size_t capacity );
void free_string_array( struct string_array_t* array );
char const * const * get_string_array( struct string_array_t const * array );
#endif
string_array.c:
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "string_array.h"
struct string_array_t {
size_t capacity;
size_t size;
char** values;
};
struct string_array_t* create_string_array( size_t capacity ) {
// ... left out ...
}
void free_string_array( struct string_array_t* array ) {
// ... left out ...
}
char const * const * get_string_array( struct string_array_t const * array ) {
return array->values;
}
The function get_string_array generates a compiler error.
I want that function to provide the caller with direct access to the underlying array, but prevent that the caller can (accidentally) mess with the internal data structure.
Hence, I want to return what I thought is (read from right-to-left) a pointer to (the beginning of an array of) constant pointers to constant chars.
The error message is:
Returning
char **constfrom a function with result typeconst char * const *discards qualifier in nested pointer types
Why do I get that message? IMHO, this should be OK, because I am not discarding any const but adding more const to it.
Because
charandconst charare two different types. Even though the const version can be easily used by the non-const version, pointers to the types are considered to be incompatible. If they weren't you could easily cast away constness without even realizing it.