Search code examples
creallocqualifiers

Realloc() discards qualifiers


I am just writing a code that has to reallocate an array X of pointers to constant strings A,B,C (see scheme below):

 _______ _______ _______     ________     ________________ 
|char* A|char* B|char* C|...|char** X|...|char*** pref_arr|...
 """"""" """"""" """""""     """"""""     """""""""""""""" 
     __                             __
    |\______________________/      |\__________/

I have the array of A,B,C, pointer to that array X and a pointer pref_arr that points to X. I had no space in the scheme, but all the chars are qualified as const.

I then have the following code

function(const char*** pref_arr, int new_length) {
    const char** new_pref_arr = realloc(**pref_arr, sizeof(const char*) * new_length);
    // some other stuff to do...
}

where I am trying to reallocate the array X to a length new_length. The problem is, that my IDE warns me that passing const char* to a void* discards qualifiers.


Solution

  • the problem here is, that you are dereferencing too much, one asterisk is precisely what you want, instead of two. See below:

    function(const char*** pref_arr) {
        const char** new_pref_arr = realloc(*pref_arr, sizeof(const char*) * N);
        // some other stuff to do...
    }
    

    What were you doing in your code was that you were trying to reallocate the string A (because **pref_arr points precisely there - through double dereferencing), which is probably not what you wanted.