arrayscstringdeclaration

C: How to correctly declare an array of strings?


I saw both :

const char*  arr = {"foo", "bar"};

and

const char*  arr[] = {"foo", "bar"};

What is the correct and generally standard way?

What is the difference between two?

what is the difference between

   const char**arr = {"foo", "bar"};

and

    const char* arr[] = {"foo", "bar"};
 

and

   const char* * const arr = {"foo", "bar"};    

and

   const char* const * const arr = {"foo", "bar"};

Solution

  • With respect to constness...

    const char* constValue = "foo";
    constValue = "bar";
    constValue[0] = 'x'; // will not work
    
    char* const constPtr = "foo";
    constPtr = "bar"; // will not work
    constPtr[0] = 'x';
    
    const char* const arr[] = { "foo", "bar", 0 }; // all const
    

    'const char* const' is is often the best solution for something fully constant. One more optimization would be to also make this static if it is declared in a local scope. The 0 ptr is useful for a sentinel value.