AVR C:const限定符在数组式查找表中的行为解析
const with Arrays in C Hey Carlos, great question — this is one of the most common pitfalls when learning C, so you’re definitely not alone in this confusion! Let’s break this down step by step to clear things up.
First: Arrays Are Not Pointers
Your core misunderstanding here comes from assuming arrays are identical to pointers — they’re not! While array names decay (implicitly convert) to pointers to their first element in most contexts, they’re fundamentally different types. An array has a fixed size and occupies a contiguous block of memory, whereas a pointer is a variable that holds a memory address.
What const uint8_t data[] = { ... } Actually Means
When you declare an array with const like this:
const uint8_t data[] = { 15, 3, 41, 76, 2, 9, 5 };
The const qualifier applies to each element of the array, not to a "pointer" representing the array. This means:
- You cannot modify any element of
data(e.g.,data[2] = 100;will throw a compiler error) - Reading elements (like
val = data[5];) is totally allowed —constonly restricts writes, not reads - The array name
dataitself is an immutable l-value (you can’t dodata++or reassign it to point elsewhere, which is different from a regular pointer)
How This Differs from const Pointers
To clarify the distinction, let’s compare with pointer declarations:
const uint8_t *ptr = data;: This is a pointer toconst uint8_t. You can change whereptrpoints (e.g.,ptr++to point to the next element), but you can’t modify the data it points to.uint8_t *const ptr = data;: This is aconstpointer touint8_t. You can’t change whereptrpoints, but you can modify the data at that address.const uint8_t *const ptr = data;: Aconstpointer toconstdata — neither the pointer nor the data can be modified.
Recapping Your Original Question
Your initial thought that "pointer itself不可修改但内容可改" applies to the uint8_t *const ptr case, not to the array declaration. For the array with const, the reverse is true: the elements (content) are read-only, and the array’s "identity" (its base address) can’t be changed either (since it’s not a variable pointer).
内容的提问来源于stack exchange,提问作者Carlos M.

