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.
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:
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 −.
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.
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.
If you actually need a pointer to an array, as your title suggests, then this is the syntax:
const char* const (*ptr)[4] = &sessionList;
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;
The same type as you declared for the array elements, with an extra *
added:
const char* const *
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With