Search code examples
cpointersstructconstants

How do I get a const pointer to a const struct?


I like to create scenarios in my code where I declare a static global struct inside a .c file that everyone will share, it contains configuration stuff. Right underneath the declaration, I'll create a constant pointer to this struct and put this in the .h file so that everyone can get access to it.

Sometimes, within a .c file, I like to have a global pointer to the specific configuration that that .c file cares about, that way I don't have constantly keep referencing the global struct, because sometimes I'll get this configuration from a different source on different projects.

The issue that I have is that I can't define this "local global" pointer because the initializer element is not constant. Here is an example.

typedef struct
{
    int Value;
} mystruct_t, *pmystruct_t;

static const mystruct_t GlobalStruct;
const pmystruct_t pGlobalStruct = &GlobalStruct;

const int *ValuePtr = &pGlobalStruct->Value;

int main()
{
    *ValuePtr = 10;

    return 0;
}

I tried reading on the const keywords for pointer in C, and I thought I understood it, but apparently it's still a mystery to me. The line of code that I tried, and may gotten me closer to that piece of code to compile is

const mystruct_t const *pGlobalStruct = &GlobalStruct;

However, it still doesn't compile because ValuePtr initializer element is not constant (the error I get).

The end goal here is to have ValuePtr be a constant, where no one can change where it is pointing to, but allow change the elements of the struct that it is pointing to.

EDIT: I want ValuePtr to use pGlobalStruct


Solution

  • The definition

    const pmystruct_t pGlobalStruct = &GlobalStruct;
    

    makes the variable (the pointer itself) pGlobalStruct constant, not the structure that it points to.

    This is only one of the many flaws that hiding pointers behind type-aliases have.

    And to make the definition of ValuePtr valid as well, then you need to make both the pointer variable as well as the structure it points to constant:

    const mystruct_t * const pGlobalStruct = &GlobalStruct;
    

    Now pGlobalStruct is a constant pointer to a constant mystruct_t object.