Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointer to const array of const pointers

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.

like image 805
Neil Avatar asked Jun 23 '16 18:06

Neil


People also ask

What is a pointer to a const value in C?

A pointer to a const value is a (non-const) pointer that points to a constant value. To declare a pointer to a const value, use the const keyword before the data type: In the above example, ptr points to a const int. So far, so good, right? Now consider the following example:

What is the first pointer to an array in C?

Pointer to an Array in C. balance is a pointer to &balance[0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p as the address of the first element of balance −.

Can We set a non-const pointer to a const pointer?

Hypothetically, if we could set a non-const pointer to a const value, then we would be able perform indirection through the non-const pointer and change the value. That would violate the intention of const. A pointer to a const value is a (non-const) pointer that points to a constant value.

What is an array of 10 Constant pointers to a character?

The above statement defines argv to be an array of 10 constant pointers to a character. This means that you have to initialize the array and cannot later change the pointers to point to a different character. However, this has nothing to do with the address of the array elements.


3 Answers

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

const char* const (*ptr)[4] = &sessionList;
like image 163
juanchopanza Avatar answered Nov 02 '22 03:11

juanchopanza


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; 
like image 20
R Sahu Avatar answered Nov 02 '22 02:11

R Sahu


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

const char* const *
like image 42
Chris Dodd Avatar answered Nov 02 '22 02:11

Chris Dodd