Search code examples
c++pointersfunction-prototypes

How to initialise and access a const char* const*


I saw a C++ code where a struct is defined as below with weird const char* const*

struct TestStruct {
    const char* const* text; 
    void* data;
};

I need to use the above struct and return an object of it from a function. But for that how to initialise the text variable to a constant string? Also, how to access the string pointed by text from the caller function.

TestStruct TestFunction() {
    TestStruct struct_obj;
    // TODO: how to assign struct_obj.text 
}

int main() {
    TestStruct struct_obj = TestFunction();
    // TODO: how to access struct_obj.text
}

Solution

  • Constants are immutable, so they cannot be assigned to. They can only be initialized. To return such a struct from a function you can use aggregate initialization (curly brace initialization). This struct can be initialized with any char**, but the one accessing it can only read from the char**, but cannot modify it.

    TestStruct TestFunction() 
    {
        char** lines = new char*[2];
        // Work with char** stored in lines
        *(lines + 0) = new char[10];
        *(lines + 1) = new char[20];
        void* data = nullptr;
        return TestStruct{ lines , data };
    }
    
    int main()
    {
       TestStruct my_struct = TestFunction();
       // const char* const * means it's an immutable array of immutable CStrings
       const char* line_one = *my_struct.text;
       const char* line_two = *(my_struct.text + 1);
      
       std::cout << line_one << std::endl;
       std::cout << line_two << std::endl;
    }
    
    

    Edit: I decided to clarify a bit further.

    "const char* const *" means A pointer-reference to an immutable table of strings. This means that the reference itself can be changed to refer to some other table at any time. The maximum level of constness is "const char * const * const" which reads as A pointer-constant-reference to an immutable table. A pointer-constant-reference means it can not point to any other table once constructed and if this was a member of a struct it definitely needs to be aggregate initialized or at least default constructed