7

I've created a const array of const pointers like so:

const char* const sessionList[] = {
    dataTable0,
    dataTable1,
    dataTable2,
    dataTable3
};

What is the correct syntax for a regular non-const pointer to this array? I thought it would be const char**, but the compiler thinks otherwise.

5
  • Technically, your const char * * would be equivalent to your array, since this is what your array will decay to when passed to a function. You'd need an extra indirection to get a pointer to the array. Or something like const char * [] *, but I'm not sure if that one is valid Commented Jun 23, 2016 at 18:06
  • 1
    It looks like the type of &sessionList is const char * const (*)[4], but I'm struggling to declare a variable with such a type. Commented Jun 23, 2016 at 18:09
  • You shoud clarify whether you want a pointer to an array or a pointer to an element of an array. Those two are different things. Commented Jun 23, 2016 at 18:12
  • @KABoissonneault: The array decays to const char * const * when you use it in most contexts (everything except sizeof, decltype and &) Commented Jun 23, 2016 at 18:12
  • @ChrisDodd You're right, I was missing a const Commented Jun 23, 2016 at 18:13

3 Answers 3

6

If you actually need a pointer to an array, as your title suggests, then this is the syntax:

const char* const (*ptr)[4] = &sessionList;
Sign up to request clarification or add additional context in comments.

Comments

5
const char* const sessionList[] = { ... };

is better written as:

char const* const sessionList[] = { ... };

Type of sessionList[0] is char const* const.
Hence, type of &sessionList[0] is char const* const*.

You can use:

char const* const* ptr = &sessionList[0]; 

or

char const* const* ptr = sessionList; 

That declares a pointer to the elements of sessionList. If you want to declare a pointer to the entire array, it needs to be:

char const* const (*ptr)[4] = &sessionList; 

Comments

2

The same type as you declared for the array elements, with an extra * added:

const char* const *

1 Comment

@juanchopanza: That's a pointer type that can point at any element of the array, which is usually what people mean by the term 'pointer to the array' -- the pointer type that the array name turns into when you use it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.